cereeenn120 commited on
Commit
34bd4b4
·
1 Parent(s): d1d1729

Fix removing last user message when reverting the ai response

Browse files
Files changed (4) hide show
  1. engine/chat.py +28 -3
  2. frontend/app.js +200 -24
  3. frontend/styles.css +55 -4
  4. server.py +48 -6
engine/chat.py CHANGED
@@ -13,6 +13,7 @@ Separation of concerns:
13
  """
14
 
15
  import logging
 
16
  from huggingface_hub import InferenceClient
17
  from engine.memory import sync_history, append_exchange, bounded_recent_context
18
  from engine.memory_jobs import schedule_memory_update
@@ -46,6 +47,7 @@ def generate_response(
46
  language: str = "English",
47
  translation_model: str | None = None,
48
  use_translator: bool = False,
 
49
  ):
50
  """
51
  Core streaming generator.
@@ -126,6 +128,9 @@ def generate_response(
126
  # Translate user message → English before sending to main model
127
  logger.debug(f"[Chat] Translating user message: {message[:80]!r}")
128
  en_message = translate_to_english(message, language, translation_client, translation_model)
 
 
 
129
  logger.debug(f"[Chat] User message (EN): {en_message[:80]!r}")
130
  prompt_language = "English" # main model always responds in English
131
  else:
@@ -174,6 +179,8 @@ def generate_response(
174
  ):
175
  if chunk.choices and chunk.choices[0].delta.content:
176
  raw_response += chunk.choices[0].delta.content
 
 
177
  else:
178
  # Stream tokens in real time
179
  for chunk in _chat_completion(
@@ -188,24 +195,42 @@ def generate_response(
188
  ):
189
  if chunk.choices and chunk.choices[0].delta.content:
190
  raw_response += chunk.choices[0].delta.content
 
 
191
  yield raw_response
192
 
193
  except Exception as e:
194
  logger.error(f"[Chat] LLM error: {e}", exc_info=True)
195
- error_note = "\n\n*(The model did not respond. Please try again.)*"
196
- yield (raw_response + error_note) if raw_response else error_note.strip()
 
 
 
 
 
 
 
 
 
197
  return
198
 
199
  logger.info(f"[Chat] Stream complete: {len(raw_response)} chars generated")
200
 
 
 
 
 
201
  if not raw_response.strip():
202
- yield "*(The model returned an empty response. Please try again.)*"
203
  return
204
 
205
  # ── Translate response → user's language, format, yield ───────────────────
206
  if use_translation:
207
  logger.debug(f"[Chat] Translating response → {language} ({len(raw_response)} chars)")
208
  final_text = translate_from_english(raw_response, language, translation_client, translation_model)
 
 
 
209
  else:
210
  final_text = raw_response
211
 
 
13
  """
14
 
15
  import logging
16
+ import time
17
  from huggingface_hub import InferenceClient
18
  from engine.memory import sync_history, append_exchange, bounded_recent_context
19
  from engine.memory_jobs import schedule_memory_update
 
47
  language: str = "English",
48
  translation_model: str | None = None,
49
  use_translator: bool = False,
50
+ deadline: float | None = None,
51
  ):
52
  """
53
  Core streaming generator.
 
128
  # Translate user message → English before sending to main model
129
  logger.debug(f"[Chat] Translating user message: {message[:80]!r}")
130
  en_message = translate_to_english(message, language, translation_client, translation_model)
131
+ if deadline is not None and time.monotonic() >= deadline:
132
+ yield "[[CHAT_ERROR:timeout]]"
133
+ return
134
  logger.debug(f"[Chat] User message (EN): {en_message[:80]!r}")
135
  prompt_language = "English" # main model always responds in English
136
  else:
 
179
  ):
180
  if chunk.choices and chunk.choices[0].delta.content:
181
  raw_response += chunk.choices[0].delta.content
182
+ if deadline is not None and time.monotonic() >= deadline:
183
+ raise TimeoutError("The model response exceeded its deadline.")
184
  else:
185
  # Stream tokens in real time
186
  for chunk in _chat_completion(
 
195
  ):
196
  if chunk.choices and chunk.choices[0].delta.content:
197
  raw_response += chunk.choices[0].delta.content
198
+ if deadline is not None and time.monotonic() >= deadline:
199
+ raise TimeoutError("The model response exceeded its deadline.")
200
  yield raw_response
201
 
202
  except Exception as e:
203
  logger.error(f"[Chat] LLM error: {e}", exc_info=True)
204
+ status = getattr(e, "status_code", getattr(getattr(e, "response", None), "status_code", None))
205
+ detail = str(e).casefold()
206
+ if deadline is not None and time.monotonic() >= deadline:
207
+ code = "timeout"
208
+ elif status in (429, 503) or any(word in detail for word in ("rate limit", "too busy", "overloaded", "capacity")):
209
+ code = "busy"
210
+ elif status in (408, 504) or isinstance(e, (TimeoutError,)) or any(word in detail for word in ("timeout", "timed out", "deadline")):
211
+ code = "timeout"
212
+ else:
213
+ code = "no_response"
214
+ yield f"[[CHAT_ERROR:{code}]]"
215
  return
216
 
217
  logger.info(f"[Chat] Stream complete: {len(raw_response)} chars generated")
218
 
219
+ if deadline is not None and time.monotonic() >= deadline:
220
+ yield "[[CHAT_ERROR:timeout]]"
221
+ return
222
+
223
  if not raw_response.strip():
224
+ yield "[[CHAT_ERROR:empty]]"
225
  return
226
 
227
  # ── Translate response → user's language, format, yield ───────────────────
228
  if use_translation:
229
  logger.debug(f"[Chat] Translating response → {language} ({len(raw_response)} chars)")
230
  final_text = translate_from_english(raw_response, language, translation_client, translation_model)
231
+ if deadline is not None and time.monotonic() >= deadline:
232
+ yield "[[CHAT_ERROR:timeout]]"
233
+ return
234
  else:
235
  final_text = raw_response
236
 
frontend/app.js CHANGED
@@ -33,6 +33,12 @@ let activeCharacter = null;
33
  let messages = [];
34
  let settings = readSettings();
35
  let draftSettings = null;
 
 
 
 
 
 
36
  let busy = false;
37
  let toastTimer = null;
38
 
@@ -49,6 +55,21 @@ function readSettings() {
49
  }
50
  }
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  function sessionId() {
53
  let id = sessionStorage.getItem("ccb.session");
54
  if (!id || !/^[0-9a-f]{32}$/.test(id)) {
@@ -70,11 +91,22 @@ function currentCharacter() {
70
  }
71
 
72
  async function api(path, body) {
73
- const response = await fetch(path, body ? {
 
 
 
 
74
  method: "POST",
75
  headers: { "Content-Type": "application/json" },
76
  body: JSON.stringify(body),
77
- } : undefined);
 
 
 
 
 
 
 
78
  const type = response.headers.get("content-type") || "";
79
  const result = type.includes("application/json") ? await response.json() : await response.text();
80
  if (!response.ok) throw new Error(result?.error || `Request failed (${response.status}).`);
@@ -197,6 +229,58 @@ function beginConfigurations(destination) {
197
  renderConfigurations();
198
  }
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  function renderConfigurations() {
201
  screen = "configurations";
202
  const availableModels = draftSettings.matureContent ? catalog.models : catalog.safe_models;
@@ -246,11 +330,13 @@ function renderRequests() {
246
  function messageHTML(message, index) {
247
  const assistant = message.role === "assistant";
248
  const character = currentCharacter();
249
- const isLastAssistant = assistant && !messages.slice(index + 1).some((item) => item.role === "assistant");
 
 
250
  return `<article class="message-row ${assistant ? "assistant" : "user"}">
251
  ${assistant ? `<img class="message-avatar" src="${escapeHTML(character?.portrait_image || "")}" alt="">` : ""}
252
  <div class="message-content"><div class="message-bubble">${formatMessage(message.content)}</div>
253
- ${assistant ? `<div class="message-tools">${iconButton("copy-message", "Copy message", "copy", `data-index="${index}"`)}${iconButton("regenerate", "Regenerate response", "retry", isLastAssistant && !busy ? "" : "disabled")}${iconButton("undo", "Undo last exchange", "undo", isLastAssistant && !busy ? "" : "disabled")}</div>` : ""}
254
  </div>
255
  </article>`;
256
  }
@@ -262,10 +348,12 @@ function renderChat() {
262
  const history = messages.map(messageHTML).join("");
263
  appRoot.innerHTML = `
264
  <main class="chat-screen"><div class="chat-layout">
265
- <aside class="character-rail">
266
- ${character.body_image ? `<img class="rail-image" src="${escapeHTML(character.body_image)}" alt="${escapeHTML(character.name)}">` : ""}<div class="rail-shade"></div>
267
- <div class="rail-title"><h2>${escapeHTML(character.name)}</h2><p>${escapeHTML(character.role || character.description)}</p></div>
268
- <button class="rail-config" data-action="chat-config">${ICONS.settings}<span>Configurations</span></button>
 
 
269
  </aside>
270
  <section class="chat-panel">
271
  <header class="chat-header">
@@ -274,7 +362,7 @@ function renderChat() {
274
  <div class="chat-actions">${iconButton("share-chat", "Share conversation", "share")}${iconButton("clear-chat", "Clear conversation", "clear")}${iconButton("copy-chat", "Copy conversation", "copy")}${iconButton("save-chat", "Download save file", "save")}</div>
275
  </header>
276
  <div id="chat-history" class="chat-history">${history || `<div class="empty-note">Say hello to start a conversation.</div>`}${busy ? `<div class="typing-indicator">${escapeHTML(character.name)} is thinking…</div>` : ""}</div>
277
- <form id="chat-form" class="chat-composer"><div id="chat-error" class="chat-error"></div><div class="compose-box"><textarea id="chat-message" rows="1" maxlength="32000" placeholder="Write a message…" ${busy ? "disabled" : ""}></textarea><button class="send-btn" type="submit" aria-label="Send" ${busy ? "disabled" : ""}>${ICONS.send}</button></div><div class="composer-hint">Enter to send · Shift + Enter for a new line</div></form>
278
  </section>
279
  </div></main>`;
280
  const historyNode = document.getElementById("chat-history");
@@ -290,6 +378,8 @@ async function beginNewChat() {
290
  sessionStorage.setItem("ccb.session", crypto.randomUUID().replaceAll("-", ""));
291
  const character = currentCharacter();
292
  messages = [{ role: "assistant", content: character.greeting || "Hello." }];
 
 
293
  busy = false;
294
  renderChat();
295
  try {
@@ -303,20 +393,23 @@ async function beginNewChat() {
303
 
304
  async function sendMessage(text, previousHistory = messages) {
305
  if (busy || !text.trim()) return;
306
- const character = currentCharacter();
307
  const content = text.trim();
308
  const history = previousHistory.map((message) => ({ role: message.role, content: message.content }));
309
  messages = [...history, { role: "user", content }];
 
 
310
  busy = true;
311
  renderChat();
312
  try {
313
  const result = await api("/api/chat", {
314
  session_id: sessionId(), character_id: activeCharacter,
315
- history, message: content, settings,
316
  });
317
  messages = result.conversation?.recent_messages || [...messages, { role: "assistant", content: result.reply }];
318
  } catch (error) {
319
- messages = [...messages, { role: "assistant", content: `*${error.message}*` }];
 
 
320
  } finally {
321
  busy = false;
322
  renderChat();
@@ -332,6 +425,11 @@ async function loadSave(file) {
332
  sessionStorage.setItem("ccb.character", activeCharacter);
333
  selectedCharacter = activeCharacter;
334
  messages = result.conversation.recent_messages || [];
 
 
 
 
 
335
  busy = false;
336
  renderChat();
337
  } catch (error) {
@@ -341,11 +439,12 @@ async function loadSave(file) {
341
 
342
  async function clearChat() {
343
  if (!confirm("Clear this conversation?")) return;
344
- const character = currentCharacter();
345
  try {
346
- await api("/api/clear", { session_id: sessionId(), character_id: activeCharacter });
347
- messages = [{ role: "assistant", content: character?.greeting || "Hello." }];
348
- await api("/api/sync", { session_id: sessionId(), character_id: activeCharacter, history: messages });
 
 
349
  renderChat();
350
  } catch (error) { toast(error.message); }
351
  }
@@ -355,11 +454,13 @@ async function undoLastExchange() {
355
  let index = -1;
356
  for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") { index = i; break; }
357
  if (index < 0) return;
 
 
358
  messages = messages.slice(0, index);
359
  try {
360
  await api("/api/sync", { session_id: sessionId(), character_id: activeCharacter, history: messages });
361
  renderChat();
362
- } catch (error) { toast(error.message); }
363
  }
364
 
365
  async function regenerateLast() {
@@ -368,15 +469,21 @@ async function regenerateLast() {
368
  for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") { index = i; break; }
369
  if (index < 0) return;
370
  const userMessage = messages[index].content;
371
- await api("/api/sync", { session_id: sessionId(), character_id: activeCharacter, history: messages.slice(0, index + 1) });
372
- await sendMessage(userMessage, messages.slice(0, index));
 
 
 
 
 
 
373
  }
374
 
375
  async function saveChat() {
376
  try {
377
  const response = await fetch("/api/save", {
378
  method: "POST", headers: { "Content-Type": "application/json" },
379
- body: JSON.stringify({ session_id: sessionId(), character_id: activeCharacter }),
380
  });
381
  if (!response.ok) {
382
  const error = await response.json();
@@ -419,7 +526,35 @@ appRoot.addEventListener("click", async (event) => {
419
  if (action === "new-chat") { selectedCategory = null; selectedGroup = null; selectedCharacter = null; return renderLibrary(); }
420
  if (action === "load-chat") { document.getElementById("save-upload").click(); return; }
421
  if (action === "configurations") return beginConfigurations("home");
422
- if (action === "chat-config") return beginConfigurations("chat");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
423
  if (action === "requests") return renderRequests();
424
  if (action === "back-home") return renderHome();
425
  if (action === "start-chat") return beginNewChat();
@@ -432,8 +567,8 @@ appRoot.addEventListener("click", async (event) => {
432
  return returnScreen === "chat" ? renderChat() : renderHome();
433
  }
434
  if (action === "exit") {
435
- localStorage.removeItem("ccb.settings"); sessionStorage.removeItem("ccb.session"); sessionStorage.removeItem("ccb.character");
436
- settings = { ...DEFAULT_SETTINGS }; activeCharacter = null; messages = [];
437
  toast("Settings reset."); return renderHome();
438
  }
439
  if (action === "share-chat") {
@@ -469,6 +604,28 @@ appRoot.addEventListener("change", (event) => {
469
  draftSettings.translationEnabled = translation;
470
  }
471
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  });
473
 
474
  appRoot.addEventListener("submit", async (event) => {
@@ -487,6 +644,22 @@ appRoot.addEventListener("submit", async (event) => {
487
  input.value = "";
488
  await sendMessage(text);
489
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  });
491
 
492
  appRoot.addEventListener("keydown", (event) => {
@@ -498,12 +671,15 @@ appRoot.addEventListener("keydown", (event) => {
498
 
499
  document.addEventListener("change", (event) => {
500
  if (event.target.id === "save-upload") loadSave(event.target.files?.[0]);
 
501
  });
502
 
503
  document.addEventListener("keydown", (event) => {
504
  if (event.key === "Escape" && screen === "configurations") {
505
  draftSettings = null;
506
- returnScreen === "chat" ? renderChat() : renderHome();
 
 
507
  }
508
  });
509
 
 
33
  let messages = [];
34
  let settings = readSettings();
35
  let draftSettings = null;
36
+ let persona = readPersona();
37
+ let draftPersona = null;
38
+ let chatConversation = null;
39
+ let activeChatTab = "chat-settings";
40
+ let pendingDraft = "";
41
+ let chatNotice = "";
42
  let busy = false;
43
  let toastTimer = null;
44
 
 
55
  }
56
  }
57
 
58
+ function readPersona() {
59
+ try { return JSON.parse(sessionStorage.getItem("ccb.persona") || "{}"); }
60
+ catch { return {}; }
61
+ }
62
+
63
+ function resetBrowserSession() {
64
+ localStorage.removeItem("ccb.settings");
65
+ sessionStorage.removeItem("ccb.session");
66
+ sessionStorage.removeItem("ccb.character");
67
+ sessionStorage.removeItem("ccb.persona");
68
+ sessionStorage.removeItem("ccb.requestDraft");
69
+ }
70
+
71
+ window.addEventListener("beforeunload", resetBrowserSession);
72
+
73
  function sessionId() {
74
  let id = sessionStorage.getItem("ccb.session");
75
  if (!id || !/^[0-9a-f]{32}$/.test(id)) {
 
91
  }
92
 
93
  async function api(path, body) {
94
+ const controller = path === "/api/chat" ? new AbortController() : null;
95
+ const timeout = controller ? setTimeout(() => controller.abort(), 60_000) : null;
96
+ let response;
97
+ try {
98
+ response = await fetch(path, body ? {
99
  method: "POST",
100
  headers: { "Content-Type": "application/json" },
101
  body: JSON.stringify(body),
102
+ signal: controller?.signal,
103
+ } : { signal: controller?.signal });
104
+ } catch (error) {
105
+ if (controller?.signal.aborted) throw new Error("The model did not respond within 60 seconds. Your message is saved as a draft; please try again.");
106
+ throw error;
107
+ } finally {
108
+ if (timeout) clearTimeout(timeout);
109
+ }
110
  const type = response.headers.get("content-type") || "";
111
  const result = type.includes("application/json") ? await response.json() : await response.text();
112
  if (!response.ok) throw new Error(result?.error || `Request failed (${response.status}).`);
 
229
  renderConfigurations();
230
  }
231
 
232
+ async function beginChatConfigurations() {
233
+ pendingDraft = document.getElementById("chat-message")?.value ?? pendingDraft;
234
+ activeChatTab = "chat-settings";
235
+ draftSettings = { ...settings };
236
+ draftPersona = { ...persona };
237
+ try {
238
+ chatConversation = await api(`/api/conversation?session_id=${sessionId()}&character_id=${encodeURIComponent(activeCharacter)}`);
239
+ renderChatConfigurations();
240
+ } catch (error) { toast(error.message); }
241
+ }
242
+
243
+ function renderChatConfigurations() {
244
+ screen = "chat-configs";
245
+ const tabs = [
246
+ ["chat-settings", "Chat settings"], ["persona", "Persona"], ["relationship", "Relationship"],
247
+ ["memories", "Memories"], ["save-load", "Save / Load"],
248
+ ];
249
+ const content = renderChatConfigTab();
250
+ appRoot.innerHTML = `
251
+ <main class="config-overlay"><section class="config-window" role="dialog" aria-modal="true" aria-labelledby="chat-config-title">
252
+ <header class="config-window-header"><div><div class="eyebrow">${escapeHTML(currentCharacter()?.name || "Chat")}</div><h2 id="chat-config-title">Configurations</h2></div><button class="icon-btn" data-action="close-chat-config" data-tooltip="Close" aria-label="Close">×</button></header>
253
+ <nav class="config-tabs" role="tablist">${tabs.map(([id, label]) => `<button class="config-tab ${activeChatTab === id ? "active" : ""}" role="tab" aria-selected="${activeChatTab === id}" data-action="config-tab" data-tab="${id}">${label}</button>`).join("")}</nav>
254
+ <div class="config-window-content">${content}</div>
255
+ ${activeChatTab === "chat-settings" ? `<footer class="config-window-footer"><button class="text-btn" data-action="close-chat-config">Back</button><button class="primary-btn" data-action="chat-config-save">Save</button></footer>` : ""}
256
+ </section></main>`;
257
+ }
258
+
259
+ function renderChatConfigTab() {
260
+ if (activeChatTab === "chat-settings") {
261
+ const choices = draftSettings.matureContent ? catalog.models : catalog.safe_models;
262
+ if (!choices.some((item) => item.id === draftSettings.model)) draftSettings.model = DEFAULT_SETTINGS.model;
263
+ return `<div class="config-tab-panel"><p class="subtle">Choose the language and model used for this conversation.</p>
264
+ <div class="settings-form"><div class="field"><label for="chat-language">Chat language</label><select id="chat-language">${catalog.languages.map((language) => `<option ${language === draftSettings.language ? "selected" : ""}>${escapeHTML(language)}</option>`).join("")}</select></div>
265
+ <div class="field"><label for="chat-model">Model</label><select id="chat-model">${choices.map((item) => `<option value="${escapeHTML(item.id)}" ${item.id === draftSettings.model ? "selected" : ""}>${escapeHTML(item.label)}</option>`).join("")}</select></div>
266
+ ${switchRow("chat-translation", "Translation model", "Use a separate model to translate messages.", draftSettings.translationEnabled)}
267
+ ${switchRow("chat-mature", "Mature content models", "Include abliterated and unrestricted models in the list.", draftSettings.matureContent)}</div></div>`;
268
+ }
269
+ if (activeChatTab === "persona") {
270
+ const fields = [["name", "Name"], ["age", "Age"], ["gender", "Gender"], ["personality", "Personality"], ["background", "Background"]];
271
+ return `<div class="config-tab-panel"><p class="subtle">This profile gives the character context about you in roleplay.</p><form id="persona-form" class="persona-form">${fields.map(([key, label]) => `<div class="field"><label for="persona-${key}">${label}</label>${["personality", "background"].includes(key) ? `<textarea id="persona-${key}" name="${key}" maxlength="4000">${escapeHTML(draftPersona[key] || "")}</textarea>` : `<input id="persona-${key}" name="${key}" maxlength="4000" value="${escapeHTML(draftPersona[key] || "")}">`}</div>`).join("")}<button class="primary-btn" type="submit">Save persona</button></form></div>`;
272
+ }
273
+ if (activeChatTab === "relationship") {
274
+ const enabled = chatConversation?.relationship?.enabled || { romance: true, attraction: true };
275
+ return `<div class="config-tab-panel"><p class="subtle">Track these relationship developments independently as the conversation evolves.</p><div class="settings-form">${switchRow("romance-enabled", "Romantic closeness", "Track romantic closeness over time.", enabled.romance)}${switchRow("attraction-enabled", "Sexual attraction", "Track sexual attraction over time.", enabled.attraction)}</div><p class="settings-tip">Both are enabled by default. Turning one off removes its saved events.</p></div>`;
276
+ }
277
+ if (activeChatTab === "memories") {
278
+ const memories = chatConversation?.long_term_memory || [];
279
+ return `<div class="config-tab-panel"><p class="subtle">Review the facts saved about this conversation.</p><div class="memory-list">${memories.length ? memories.map((item) => `<article class="memory-item"><p>${escapeHTML(item.content)}</p><span>${escapeHTML(item.importance || "saved")}</span><div><button class="text-btn" data-action="edit-memory" data-memory-id="${escapeHTML(item.id)}">Edit</button><button class="text-btn danger-btn" data-action="forget-memory" data-memory-id="${escapeHTML(item.id)}">Forget</button></div></article>`).join("") : `<div class="empty-note">No memories have been saved yet.</div>`}</div><form id="memory-form" class="memory-form"><div class="field"><label for="memory-content">Add a memory</label><textarea id="memory-content" maxlength="2000" placeholder="A useful fact to remember…" required></textarea></div><button class="primary-btn" type="submit">Remember</button></form></div>`;
280
+ }
281
+ return `<div class="config-tab-panel save-load-panel"><p class="subtle">Download this conversation as JSON or load a save file into the current chat.</p><button class="secondary-btn" data-action="save-chat">Download save file</button><label class="field upload-field"><span class="field-title">Load a save file</span><input id="chat-save-upload" type="file" accept=".json,application/json"></label><div id="save-load-note" class="settings-tip"></div></div>`;
282
+ }
283
+
284
  function renderConfigurations() {
285
  screen = "configurations";
286
  const availableModels = draftSettings.matureContent ? catalog.models : catalog.safe_models;
 
330
  function messageHTML(message, index) {
331
  const assistant = message.role === "assistant";
332
  const character = currentCharacter();
333
+ const lastAssistantIndex = messages.reduce((found, item, itemIndex) => item.role === "assistant" ? itemIndex : found, -1);
334
+ const hasUserMessage = messages.slice(0, index).some((item) => item.role === "user");
335
+ const isLastAssistant = assistant && index === lastAssistantIndex && messages.at(-1)?.role === "assistant" && hasUserMessage && !pendingDraft;
336
  return `<article class="message-row ${assistant ? "assistant" : "user"}">
337
  ${assistant ? `<img class="message-avatar" src="${escapeHTML(character?.portrait_image || "")}" alt="">` : ""}
338
  <div class="message-content"><div class="message-bubble">${formatMessage(message.content)}</div>
339
+ ${assistant ? `<div class="message-tools">${iconButton("copy-message", "Copy message", "copy", `data-index="${index}"`)}${isLastAssistant && !busy ? `${iconButton("regenerate", "Regenerate response", "retry")}${iconButton("undo", "Undo last exchange", "undo")}` : ""}</div>` : ""}
340
  </div>
341
  </article>`;
342
  }
 
348
  const history = messages.map(messageHTML).join("");
349
  appRoot.innerHTML = `
350
  <main class="chat-screen"><div class="chat-layout">
351
+ <aside class="character-sidebar">
352
+ <div class="character-rail">
353
+ ${character.body_image ? `<img class="rail-image" src="${escapeHTML(character.body_image)}" alt="${escapeHTML(character.name)}">` : `<div class="empty-note">No character image available.</div>`}<div class="rail-shade"></div>
354
+ <div class="rail-title"><h2>${escapeHTML(character.name)}</h2><p>${escapeHTML(character.role || character.description)}</p></div>
355
+ </div>
356
+ <div class="rail-actions"><button class="rail-config" data-action="chat-config">${ICONS.settings}<span>Configurations</span></button><button class="rail-exit" data-action="exit-chat">${ICONS.exit}<span>Exit Chat</span></button></div>
357
  </aside>
358
  <section class="chat-panel">
359
  <header class="chat-header">
 
362
  <div class="chat-actions">${iconButton("share-chat", "Share conversation", "share")}${iconButton("clear-chat", "Clear conversation", "clear")}${iconButton("copy-chat", "Copy conversation", "copy")}${iconButton("save-chat", "Download save file", "save")}</div>
363
  </header>
364
  <div id="chat-history" class="chat-history">${history || `<div class="empty-note">Say hello to start a conversation.</div>`}${busy ? `<div class="typing-indicator">${escapeHTML(character.name)} is thinking…</div>` : ""}</div>
365
+ <form id="chat-form" class="chat-composer"><div id="chat-error" class="chat-error" role="status">${escapeHTML(chatNotice)}</div><div class="compose-box"><textarea id="chat-message" rows="1" maxlength="32000" placeholder="Write a message…" ${busy ? "disabled" : ""}>${escapeHTML(pendingDraft)}</textarea><button class="send-btn" type="submit" aria-label="Send" ${busy ? "disabled" : ""}>${ICONS.send}</button></div><div class="composer-hint">Enter to send · Shift + Enter for a new line</div></form>
366
  </section>
367
  </div></main>`;
368
  const historyNode = document.getElementById("chat-history");
 
378
  sessionStorage.setItem("ccb.session", crypto.randomUUID().replaceAll("-", ""));
379
  const character = currentCharacter();
380
  messages = [{ role: "assistant", content: character.greeting || "Hello." }];
381
+ pendingDraft = "";
382
+ chatNotice = "";
383
  busy = false;
384
  renderChat();
385
  try {
 
393
 
394
  async function sendMessage(text, previousHistory = messages) {
395
  if (busy || !text.trim()) return;
 
396
  const content = text.trim();
397
  const history = previousHistory.map((message) => ({ role: message.role, content: message.content }));
398
  messages = [...history, { role: "user", content }];
399
+ pendingDraft = "";
400
+ chatNotice = "";
401
  busy = true;
402
  renderChat();
403
  try {
404
  const result = await api("/api/chat", {
405
  session_id: sessionId(), character_id: activeCharacter,
406
+ history, message: content, settings, persona,
407
  });
408
  messages = result.conversation?.recent_messages || [...messages, { role: "assistant", content: result.reply }];
409
  } catch (error) {
410
+ messages = history;
411
+ pendingDraft = content;
412
+ chatNotice = error.message || "The model could not respond. Your message is saved as a draft.";
413
  } finally {
414
  busy = false;
415
  renderChat();
 
425
  sessionStorage.setItem("ccb.character", activeCharacter);
426
  selectedCharacter = activeCharacter;
427
  messages = result.conversation.recent_messages || [];
428
+ persona = result.persona || {};
429
+ sessionStorage.setItem("ccb.persona", JSON.stringify(persona));
430
+ chatConversation = result.conversation;
431
+ pendingDraft = "";
432
+ chatNotice = "";
433
  busy = false;
434
  renderChat();
435
  } catch (error) {
 
439
 
440
  async function clearChat() {
441
  if (!confirm("Clear this conversation?")) return;
 
442
  try {
443
+ const state = await api("/api/clear", { session_id: sessionId(), character_id: activeCharacter });
444
+ messages = state.recent_messages || [];
445
+ chatConversation = state;
446
+ pendingDraft = "";
447
+ chatNotice = "";
448
  renderChat();
449
  } catch (error) { toast(error.message); }
450
  }
 
454
  let index = -1;
455
  for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") { index = i; break; }
456
  if (index < 0) return;
457
+ pendingDraft = messages[index].content;
458
+ chatNotice = "Last exchange removed. Your message is ready to edit or send again.";
459
  messages = messages.slice(0, index);
460
  try {
461
  await api("/api/sync", { session_id: sessionId(), character_id: activeCharacter, history: messages });
462
  renderChat();
463
+ } catch (error) { toast(error.message); renderChat(); }
464
  }
465
 
466
  async function regenerateLast() {
 
469
  for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") { index = i; break; }
470
  if (index < 0) return;
471
  const userMessage = messages[index].content;
472
+ try {
473
+ await api("/api/sync", { session_id: sessionId(), character_id: activeCharacter, history: messages.slice(0, index + 1) });
474
+ await sendMessage(userMessage, messages.slice(0, index));
475
+ } catch (error) {
476
+ pendingDraft = userMessage;
477
+ chatNotice = error.message || "The response could not be regenerated. Your message is saved as a draft.";
478
+ renderChat();
479
+ }
480
  }
481
 
482
  async function saveChat() {
483
  try {
484
  const response = await fetch("/api/save", {
485
  method: "POST", headers: { "Content-Type": "application/json" },
486
+ body: JSON.stringify({ session_id: sessionId(), character_id: activeCharacter, persona }),
487
  });
488
  if (!response.ok) {
489
  const error = await response.json();
 
526
  if (action === "new-chat") { selectedCategory = null; selectedGroup = null; selectedCharacter = null; return renderLibrary(); }
527
  if (action === "load-chat") { document.getElementById("save-upload").click(); return; }
528
  if (action === "configurations") return beginConfigurations("home");
529
+ if (action === "chat-config") return beginChatConfigurations();
530
+ if (action === "config-tab") { activeChatTab = button.dataset.tab; return renderChatConfigurations(); }
531
+ if (action === "close-chat-config") { draftSettings = null; draftPersona = null; return renderChat(); }
532
+ if (action === "chat-config-save") {
533
+ settings = { ...draftSettings };
534
+ localStorage.setItem("ccb.settings", JSON.stringify(settings));
535
+ draftSettings = null;
536
+ return renderChat();
537
+ }
538
+ if (action === "exit-chat") {
539
+ activeCharacter = null; messages = []; pendingDraft = ""; chatNotice = "";
540
+ sessionStorage.removeItem("ccb.character");
541
+ return renderHome();
542
+ }
543
+ if (action === "forget-memory" || action === "edit-memory") {
544
+ const item = chatConversation?.long_term_memory?.find((memory) => memory.id === button.dataset.memoryId);
545
+ if (!item) return;
546
+ if (action === "forget-memory" && !confirm("Forget this memory?")) return;
547
+ const content = action === "edit-memory" ? prompt("Edit this memory", item.content) : "";
548
+ if (action === "edit-memory" && (content === null || !content.trim())) return;
549
+ try {
550
+ chatConversation = await api("/api/memory", {
551
+ session_id: sessionId(), character_id: activeCharacter,
552
+ action: action === "edit-memory" ? "edit" : "forget", memory_id: item.id, content,
553
+ });
554
+ renderChatConfigurations();
555
+ } catch (error) { toast(error.message); }
556
+ return;
557
+ }
558
  if (action === "requests") return renderRequests();
559
  if (action === "back-home") return renderHome();
560
  if (action === "start-chat") return beginNewChat();
 
567
  return returnScreen === "chat" ? renderChat() : renderHome();
568
  }
569
  if (action === "exit") {
570
+ resetBrowserSession();
571
+ settings = { ...DEFAULT_SETTINGS }; persona = {}; activeCharacter = null; messages = []; pendingDraft = ""; chatNotice = "";
572
  toast("Settings reset."); return renderHome();
573
  }
574
  if (action === "share-chat") {
 
604
  draftSettings.translationEnabled = translation;
605
  }
606
  }
607
+ if (screen === "chat-configs") {
608
+ if (event.target.id === "chat-language") draftSettings.language = event.target.value;
609
+ if (event.target.id === "chat-model") draftSettings.model = event.target.value;
610
+ if (event.target.id === "chat-translation") draftSettings.translationEnabled = event.target.checked;
611
+ if (event.target.id === "chat-mature") {
612
+ draftSettings.matureContent = event.target.checked;
613
+ renderChatConfigurations();
614
+ }
615
+ if (["romance-enabled", "attraction-enabled"].includes(event.target.id)) {
616
+ const romance = document.getElementById("romance-enabled").checked;
617
+ const attraction = document.getElementById("attraction-enabled").checked;
618
+ api("/api/relationship", { session_id: sessionId(), character_id: activeCharacter, romance, attraction })
619
+ .then((state) => { chatConversation = state; renderChatConfigurations(); })
620
+ .catch((error) => toast(error.message));
621
+ }
622
+ }
623
+ });
624
+
625
+ appRoot.addEventListener("input", (event) => {
626
+ if (screen === "chat-configs" && event.target.id.startsWith("persona-")) {
627
+ draftPersona[event.target.name] = event.target.value;
628
+ }
629
  });
630
 
631
  appRoot.addEventListener("submit", async (event) => {
 
644
  input.value = "";
645
  await sendMessage(text);
646
  }
647
+ if (event.target.id === "persona-form") {
648
+ event.preventDefault();
649
+ persona = Object.fromEntries(new FormData(event.target).entries());
650
+ draftPersona = { ...persona };
651
+ sessionStorage.setItem("ccb.persona", JSON.stringify(persona));
652
+ toast("Persona saved.");
653
+ renderChatConfigurations();
654
+ }
655
+ if (event.target.id === "memory-form") {
656
+ event.preventDefault();
657
+ const content = document.getElementById("memory-content").value;
658
+ try {
659
+ chatConversation = await api("/api/memory", { session_id: sessionId(), character_id: activeCharacter, action: "remember", content });
660
+ renderChatConfigurations();
661
+ } catch (error) { toast(error.message); }
662
+ }
663
  });
664
 
665
  appRoot.addEventListener("keydown", (event) => {
 
671
 
672
  document.addEventListener("change", (event) => {
673
  if (event.target.id === "save-upload") loadSave(event.target.files?.[0]);
674
+ if (event.target.id === "chat-save-upload") loadSave(event.target.files?.[0]);
675
  });
676
 
677
  document.addEventListener("keydown", (event) => {
678
  if (event.key === "Escape" && screen === "configurations") {
679
  draftSettings = null;
680
+ renderHome();
681
+ } else if (event.key === "Escape" && screen === "chat-configs") {
682
+ draftSettings = null; draftPersona = null; renderChat();
683
  }
684
  });
685
 
frontend/styles.css CHANGED
@@ -106,15 +106,19 @@ h2 { font-size: clamp(27px, 3vw, 40px); line-height: 1.12; margin-bottom: 10px;
106
  /* Chat room */
107
  .chat-screen { height: 100vh; min-height: 620px; padding: 18px; overflow: hidden; }
108
  .chat-layout { width: min(1480px, 100%); height: calc(100vh - 36px); min-height: 584px; margin: 0 auto; display: grid; grid-template-columns: minmax(210px, 300px) minmax(0, 1fr); gap: 17px; }
109
- .character-rail { position: relative; width: 100%; height: auto; max-height: 86vh; aspect-ratio: 9 / 16; justify-self: center; align-self: center; min-height: 0; overflow: hidden; display: flex; flex-direction: column; justify-content: flex-end; padding: 0 18px 17px; border-radius: 20px; border: 1px solid var(--line); background: #22211d; }
 
110
  .rail-image { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: top center; }
111
  .rail-shade { position: absolute; inset: 30% 0 0; background: linear-gradient(transparent, #11110feF); }
112
  .rail-title { position: relative; z-index: 1; margin-bottom: 19px; }
113
  .rail-title h2 { font-size: 23px; margin: 0 0 5px; }
114
  .rail-title p { color: #d0cabc; font-size: 12px; line-height: 1.4; margin: 0; }
115
- .rail-config { position: relative; z-index: 1; width: 100%; display: flex; align-items: center; justify-content: center; gap: 9px; padding: 11px; border-radius: 11px; border: 1px solid #ffffff26; background: #171714d9; color: var(--text); cursor: pointer; font-size: 12px; font-weight: 700; backdrop-filter: blur(12px); }
116
- .rail-config:hover { background: #39342c; border-color: #dba76f66; }
117
- .rail-config svg { width: 16px; height: 16px; fill: none; stroke: var(--accent-hi); stroke-width: 1.8; }
 
 
 
118
  .chat-panel { min-width: 0; min-height: 0; overflow: hidden; display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 20px; background: #161613; }
119
  .chat-header { min-height: 76px; display: flex; align-items: center; gap: 12px; padding: 12px 17px; border-bottom: 1px solid var(--line); background: #1b1b17; }
120
  .portrait { width: 43px; height: 43px; flex: 0 0 43px; border: 1px solid #625645; border-radius: 50%; object-fit: cover; background: #33332c; }
@@ -148,6 +152,38 @@ h2 { font-size: clamp(27px, 3vw, 40px); line-height: 1.12; margin-bottom: 10px;
148
  .send-btn svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
149
  .composer-hint { padding: 7px 5px 0; text-align: center; color: var(--faint); font-size: 10px; }
150
  .chat-error { min-height: 16px; padding: 0 4px 7px; color: var(--danger); font-size: 12px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  #toast { position: fixed; left: 50%; bottom: 22px; z-index: 100; padding: 11px 16px; border: 1px solid #5c5548; border-radius: 12px; color: var(--text); background: #28251f; font-size: 12px; box-shadow: 0 12px 35px #0008; opacity: 0; transform: translate(-50%, 10px); pointer-events: none; transition: .2s; }
152
  #toast.show { opacity: 1; transform: translate(-50%, 0); }
153
  .empty-note { padding: 14px; color: var(--faint); font-size: 12px; line-height: 1.5; }
@@ -176,13 +212,28 @@ h2 { font-size: clamp(27px, 3vw, 40px); line-height: 1.12; margin-bottom: 10px;
176
  .config-actions { position: sticky; bottom: 0; padding: 13px 0 3px; background: #191916; }
177
  .chat-screen { height: 100svh; min-height: 0; padding: 0; }
178
  .chat-layout { height: 100svh; min-height: 0; display: flex; flex-direction: column; gap: 0; }
 
179
  .character-rail { display: none; }
 
 
180
  .chat-panel { flex: 1; min-height: 0; border: 0; border-radius: 0; }
181
  .chat-header { min-height: 68px; padding: 9px 10px; }
182
  .chat-actions { gap: 0; }
183
  .chat-actions .icon-btn { width: 32px; height: 34px; }
184
  .chat-actions .icon-btn svg { width: 17px; height: 17px; }
185
  .chat-person span { max-width: 42vw; }
 
 
 
 
 
 
 
 
 
 
 
 
186
  .chat-history { padding: 19px 12px; gap: 17px; }
187
  .message-row { max-width: 96%; gap: 8px; }
188
  .message-avatar { width: 29px; height: 29px; flex-basis: 29px; }
 
106
  /* Chat room */
107
  .chat-screen { height: 100vh; min-height: 620px; padding: 18px; overflow: hidden; }
108
  .chat-layout { width: min(1480px, 100%); height: calc(100vh - 36px); min-height: 584px; margin: 0 auto; display: grid; grid-template-columns: minmax(210px, 300px) minmax(0, 1fr); gap: 17px; }
109
+ .character-sidebar { min-height: 0; display: flex; flex-direction: column; justify-content: center; gap: 11px; }
110
+ .character-rail { position: relative; width: 100%; max-height: calc(100% - 104px); aspect-ratio: 9 / 16; justify-self: center; align-self: center; min-height: 0; overflow: hidden; display: flex; flex-direction: column; justify-content: flex-end; padding: 0 18px 17px; border-radius: 20px; border: 1px solid var(--line); background: #22211d; }
111
  .rail-image { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: top center; }
112
  .rail-shade { position: absolute; inset: 30% 0 0; background: linear-gradient(transparent, #11110feF); }
113
  .rail-title { position: relative; z-index: 1; margin-bottom: 19px; }
114
  .rail-title h2 { font-size: 23px; margin: 0 0 5px; }
115
  .rail-title p { color: #d0cabc; font-size: 12px; line-height: 1.4; margin: 0; }
116
+ .rail-actions { display: grid; gap: 8px; }
117
+ .rail-config, .rail-exit { width: 100%; display: flex; align-items: center; justify-content: center; gap: 9px; padding: 11px; border-radius: 11px; border: 1px solid #ffffff26; background: #171714; color: var(--text); cursor: pointer; font-size: 12px; font-weight: 700; transition: .16s ease; }
118
+ .rail-config:hover, .rail-exit:hover { background: #39342c; border-color: #dba76f66; }
119
+ .rail-config svg, .rail-exit svg { width: 16px; height: 16px; fill: none; stroke: var(--accent-hi); stroke-width: 1.8; }
120
+ .rail-exit { color: #d2c8ba; }
121
+ .rail-exit svg { stroke: #c99a82; }
122
  .chat-panel { min-width: 0; min-height: 0; overflow: hidden; display: flex; flex-direction: column; border: 1px solid var(--line); border-radius: 20px; background: #161613; }
123
  .chat-header { min-height: 76px; display: flex; align-items: center; gap: 12px; padding: 12px 17px; border-bottom: 1px solid var(--line); background: #1b1b17; }
124
  .portrait { width: 43px; height: 43px; flex: 0 0 43px; border: 1px solid #625645; border-radius: 50%; object-fit: cover; background: #33332c; }
 
152
  .send-btn svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
153
  .composer-hint { padding: 7px 5px 0; text-align: center; color: var(--faint); font-size: 10px; }
154
  .chat-error { min-height: 16px; padding: 0 4px 7px; color: var(--danger); font-size: 12px; }
155
+ .config-overlay { position: fixed; inset: 0; z-index: 70; display: grid; place-items: center; padding: 24px; background: #080807b8; backdrop-filter: blur(9px); }
156
+ .config-window { width: min(820px, 100%); max-height: min(850px, calc(100vh - 48px)); display: flex; flex-direction: column; overflow: hidden; border: 1px solid #48463d; border-radius: 20px; background: #191916; box-shadow: 0 25px 90px #000b; }
157
+ .config-window-header { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 22px 26px 15px; }
158
+ .config-window-header h2 { margin: 5px 0 0; font-size: 28px; }
159
+ .config-tabs { display: flex; gap: 4px; padding: 0 20px; overflow-x: auto; border-bottom: 1px solid var(--line); }
160
+ .config-tab { position: relative; flex: 0 0 auto; padding: 13px 11px; border: 0; border-radius: 9px 9px 0 0; color: var(--muted); background: transparent; cursor: pointer; font-size: 12px; font-weight: 700; }
161
+ .config-tab:hover { color: var(--text); background: #25251f; }
162
+ .config-tab.active { color: var(--accent-hi); background: #25221c; }
163
+ .config-tab.active::after { position: absolute; right: 9px; bottom: 0; left: 9px; height: 2px; background: var(--accent); content: ""; }
164
+ .config-window-content { min-height: 180px; overflow: auto; padding: 22px 26px; }
165
+ .config-tab-panel > .subtle { margin-bottom: 20px; font-size: 13px; }
166
+ .config-tab-panel .settings-form { margin: 0; }
167
+ .config-window-footer { display: flex; justify-content: flex-end; gap: 10px; padding: 14px 26px 20px; border-top: 1px solid var(--line); }
168
+ .persona-form { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
169
+ .persona-form .field:nth-last-of-type(-n+2) { grid-column: 1 / -1; }
170
+ .persona-form textarea, .memory-form textarea { min-height: 88px; resize: vertical; }
171
+ .persona-form button { justify-self: end; grid-column: 1 / -1; }
172
+ .memory-list { display: grid; gap: 9px; max-height: 285px; overflow: auto; margin-bottom: 20px; }
173
+ .memory-item { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 5px 12px; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; background: #20201c; }
174
+ .memory-item p { grid-column: 1 / -1; margin: 0; color: var(--text); font-size: 13px; line-height: 1.55; }
175
+ .memory-item > span { align-self: center; color: var(--faint); font-size: 10px; text-transform: capitalize; }
176
+ .memory-item > div { display: flex; justify-content: flex-end; gap: 6px; }
177
+ .memory-item .text-btn { padding: 7px 10px; font-size: 11px; }
178
+ .danger-btn { color: var(--danger); }
179
+ .memory-form { display: flex; align-items: flex-end; gap: 12px; }
180
+ .memory-form .field { flex: 1; }
181
+ .memory-form .primary-btn { flex: 0 0 auto; }
182
+ .save-load-panel { display: grid; justify-items: start; gap: 16px; }
183
+ .save-load-panel > .subtle { margin: 0; }
184
+ .upload-field { width: 100%; margin-top: 7px; }
185
+ .upload-field input { padding: 10px; }
186
+ .settings-tip { color: var(--muted); font-size: 12px; line-height: 1.55; }
187
  #toast { position: fixed; left: 50%; bottom: 22px; z-index: 100; padding: 11px 16px; border: 1px solid #5c5548; border-radius: 12px; color: var(--text); background: #28251f; font-size: 12px; box-shadow: 0 12px 35px #0008; opacity: 0; transform: translate(-50%, 10px); pointer-events: none; transition: .2s; }
188
  #toast.show { opacity: 1; transform: translate(-50%, 0); }
189
  .empty-note { padding: 14px; color: var(--faint); font-size: 12px; line-height: 1.5; }
 
212
  .config-actions { position: sticky; bottom: 0; padding: 13px 0 3px; background: #191916; }
213
  .chat-screen { height: 100svh; min-height: 0; padding: 0; }
214
  .chat-layout { height: 100svh; min-height: 0; display: flex; flex-direction: column; gap: 0; }
215
+ .character-sidebar { display: flex; flex-direction: row; justify-content: stretch; gap: 7px; padding: 7px 9px; border-bottom: 1px solid var(--line); background: #171714; }
216
  .character-rail { display: none; }
217
+ .rail-actions { display: flex; flex: 1; gap: 7px; }
218
+ .rail-config, .rail-exit { padding: 9px 7px; font-size: 11px; }
219
  .chat-panel { flex: 1; min-height: 0; border: 0; border-radius: 0; }
220
  .chat-header { min-height: 68px; padding: 9px 10px; }
221
  .chat-actions { gap: 0; }
222
  .chat-actions .icon-btn { width: 32px; height: 34px; }
223
  .chat-actions .icon-btn svg { width: 17px; height: 17px; }
224
  .chat-person span { max-width: 42vw; }
225
+ .config-overlay { padding: 10px; }
226
+ .config-window { max-height: calc(100svh - 20px); border-radius: 16px; }
227
+ .config-window-header { padding: 17px 17px 12px; }
228
+ .config-window-header h2 { font-size: 24px; }
229
+ .config-tabs { padding: 0 8px; }
230
+ .config-tab { padding: 12px 9px; font-size: 11px; }
231
+ .config-window-content { padding: 18px 17px; }
232
+ .config-window-footer { padding: 12px 17px 15px; }
233
+ .persona-form { grid-template-columns: 1fr; }
234
+ .persona-form .field:nth-last-of-type(-n+2) { grid-column: auto; }
235
+ .memory-form { align-items: stretch; flex-direction: column; }
236
+ .memory-form .primary-btn { align-self: flex-end; }
237
  .chat-history { padding: 19px 12px; gap: 17px; }
238
  .message-row { max-width: 96%; gap: 8px; }
239
  .message-avatar { width: 29px; height: 29px; flex-basis: 29px; }
server.py CHANGED
@@ -7,6 +7,7 @@ import logging
7
  import mimetypes
8
  import os
9
  import re
 
10
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
  from pathlib import Path
12
  from urllib.parse import parse_qs, unquote, urlparse
@@ -17,9 +18,9 @@ from openai import OpenAI
17
  from engine.chat import generate_response
18
  from engine.memory import load_conversation, sync_history
19
  from engine.models import DEFAULT_MODEL, LANGUAGES, MODELS, TRANSLATION_MODEL, is_mature_model
20
- from engine.persona import get_empty_persona
21
  from engine.prompt_builder import get_avatar_path, get_portrait_path, list_characters, load_character
22
- from engine.relationship import get_default_relationship
23
  from engine.saveload import export_save, restore_save, validate_save
24
 
25
  ROOT = Path(__file__).resolve().parent
@@ -193,6 +194,10 @@ class AppHandler(BaseHTTPRequestHandler):
193
  return self._clear(data)
194
  if route == "/api/save":
195
  return self._save(data)
 
 
 
 
196
  return self._json(404, {"error": "Not found."})
197
  except ValueError as exc:
198
  return self._json(400, {"error": str(exc)})
@@ -219,19 +224,36 @@ class AppHandler(BaseHTTPRequestHandler):
219
  if selected is None or (not mature and is_mature_model(*selected)):
220
  raise ValueError("That model is unavailable with the current content setting.")
221
  use_translator = settings.get("translationEnabled") is True
 
 
 
 
222
  if use_translator and model_id.endswith(":featherless-ai"):
223
  client = OpenAI(base_url="https://router.huggingface.co/v1", api_key=HF_TOKEN, timeout=60)
224
  else:
225
  client = InferenceClient(token=HF_TOKEN, timeout=60)
 
226
  result = None
227
  for result in generate_response(
228
  message=message.strip(), character_id=character_id, client=client,
229
- session_id=session_id, history=history, persona=get_empty_persona(),
230
  model=model_id, max_tokens=700, temperature=0.7, top_p=0.95,
231
  language=language, translation_model=TRANSLATION_MODEL,
232
- use_translator=use_translator,
233
  ):
234
  pass
 
 
 
 
 
 
 
 
 
 
 
 
235
  return self._json(200, {"reply": result or "", "conversation": load_conversation(session_id, character_id)})
236
 
237
  def _load(self, data: dict):
@@ -260,13 +282,33 @@ class AppHandler(BaseHTTPRequestHandler):
260
  def _clear(self, data: dict):
261
  session_id = self._require_session(data.get("session_id"))
262
  character_id = self._require_character(data.get("character_id"))
263
- state = sync_history(session_id, character_id, [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  return self._json(200, state)
265
 
266
  def _save(self, data: dict):
267
  session_id = self._require_session(data.get("session_id"))
268
  character_id = self._require_character(data.get("character_id"))
269
- path = Path(export_save(character_id, get_empty_persona(), session_id))
 
 
 
 
270
  try:
271
  payload = path.read_bytes()
272
  finally:
 
7
  import mimetypes
8
  import os
9
  import re
10
+ import time
11
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
12
  from pathlib import Path
13
  from urllib.parse import parse_qs, unquote, urlparse
 
18
  from engine.chat import generate_response
19
  from engine.memory import load_conversation, sync_history
20
  from engine.models import DEFAULT_MODEL, LANGUAGES, MODELS, TRANSLATION_MODEL, is_mature_model
21
+ from engine.persona import PERSONA_FIELDS, validate_persona
22
  from engine.prompt_builder import get_avatar_path, get_portrait_path, list_characters, load_character
23
+ from engine.memory_controls import change_memory, set_relationship_options
24
  from engine.saveload import export_save, restore_save, validate_save
25
 
26
  ROOT = Path(__file__).resolve().parent
 
194
  return self._clear(data)
195
  if route == "/api/save":
196
  return self._save(data)
197
+ if route == "/api/memory":
198
+ return self._memory(data)
199
+ if route == "/api/relationship":
200
+ return self._relationship(data)
201
  return self._json(404, {"error": "Not found."})
202
  except ValueError as exc:
203
  return self._json(400, {"error": str(exc)})
 
224
  if selected is None or (not mature and is_mature_model(*selected)):
225
  raise ValueError("That model is unavailable with the current content setting.")
226
  use_translator = settings.get("translationEnabled") is True
227
+ persona_data = data.get("persona", {})
228
+ if not isinstance(persona_data, dict):
229
+ raise ValueError("Persona must be an object.")
230
+ persona = validate_persona({key: value for key, value in persona_data.items() if key in PERSONA_FIELDS})
231
  if use_translator and model_id.endswith(":featherless-ai"):
232
  client = OpenAI(base_url="https://router.huggingface.co/v1", api_key=HF_TOKEN, timeout=60)
233
  else:
234
  client = InferenceClient(token=HF_TOKEN, timeout=60)
235
+ deadline = time.monotonic() + 60
236
  result = None
237
  for result in generate_response(
238
  message=message.strip(), character_id=character_id, client=client,
239
+ session_id=session_id, history=history, persona=persona,
240
  model=model_id, max_tokens=700, temperature=0.7, top_p=0.95,
241
  language=language, translation_model=TRANSLATION_MODEL,
242
+ use_translator=use_translator, deadline=deadline,
243
  ):
244
  pass
245
+ if result and result.startswith("[[CHAT_ERROR:"):
246
+ code = result.removeprefix("[[CHAT_ERROR:").removesuffix("]]")
247
+ errors = {
248
+ "busy": (429, "The model is busy right now. Your message is saved as a draft; please try again shortly."),
249
+ "timeout": (504, "The model did not respond within 60 seconds. Your message is saved as a draft; please try again."),
250
+ "empty": (502, "The model returned an empty response. Your message is saved as a draft; please try again."),
251
+ "no_response": (502, "The model did not return a response. Your message is saved as a draft; please try again."),
252
+ }
253
+ status, message_text = errors.get(code, (502, "The model could not respond. Your message is saved as a draft; please try again."))
254
+ return self._json(status, {"error": message_text, "code": code})
255
+ if not isinstance(result, str) or not result.strip():
256
+ return self._json(502, {"error": "The model did not return a response. Your message is saved as a draft; please try again.", "code": "no_response"})
257
  return self._json(200, {"reply": result or "", "conversation": load_conversation(session_id, character_id)})
258
 
259
  def _load(self, data: dict):
 
282
  def _clear(self, data: dict):
283
  session_id = self._require_session(data.get("session_id"))
284
  character_id = self._require_character(data.get("character_id"))
285
+ sync_history(session_id, character_id, [])
286
+ greeting = load_character(character_id).get("greeting", "Hello.")
287
+ state = sync_history(session_id, character_id, [{"role": "assistant", "content": greeting}])
288
+ return self._json(200, state)
289
+
290
+ def _memory(self, data: dict):
291
+ session_id = self._require_session(data.get("session_id"))
292
+ character_id = self._require_character(data.get("character_id"))
293
+ state = change_memory(session_id, character_id, data.get("action"),
294
+ data.get("content", ""), data.get("memory_id"))
295
+ return self._json(200, state)
296
+
297
+ def _relationship(self, data: dict):
298
+ session_id = self._require_session(data.get("session_id"))
299
+ character_id = self._require_character(data.get("character_id"))
300
+ state = set_relationship_options(session_id, character_id,
301
+ data.get("romance"), data.get("attraction"))
302
  return self._json(200, state)
303
 
304
  def _save(self, data: dict):
305
  session_id = self._require_session(data.get("session_id"))
306
  character_id = self._require_character(data.get("character_id"))
307
+ persona = data.get("persona", {})
308
+ if not isinstance(persona, dict):
309
+ raise ValueError("Persona must be an object.")
310
+ persona = validate_persona({key: value for key, value in persona.items() if key in PERSONA_FIELDS})
311
+ path = Path(export_save(character_id, persona, session_id))
312
  try:
313
  payload = path.read_bytes()
314
  finally: