Fix guest session persistence: reuse guest by IP, extend token TTL to 7 days, enable guest titles
Browse files- backend/chat.py +1 -1
- backend/main.py +4 -9
- frontend/app.js +53 -28
- test_conversation_save.py +259 -0
backend/chat.py
CHANGED
|
@@ -252,7 +252,7 @@ class ChatHandler:
|
|
| 252 |
t.start()
|
| 253 |
|
| 254 |
title = None
|
| 255 |
-
if
|
| 256 |
title_holder: list = [None]
|
| 257 |
current_title = self.db.get_conversation_title(conversation_id)
|
| 258 |
|
|
|
|
| 252 |
t.start()
|
| 253 |
|
| 254 |
title = None
|
| 255 |
+
if existing_msg_count % 6 == 0:
|
| 256 |
title_holder: list = [None]
|
| 257 |
current_title = self.db.get_conversation_title(conversation_id)
|
| 258 |
|
backend/main.py
CHANGED
|
@@ -117,6 +117,7 @@ class UserLogin(BaseModel):
|
|
| 117 |
class TokenResponse(BaseModel):
|
| 118 |
access_token: str
|
| 119 |
token_type: str = "bearer"
|
|
|
|
| 120 |
|
| 121 |
|
| 122 |
class ChatMessage(BaseModel):
|
|
@@ -502,19 +503,13 @@ async def create_guest(request: Request):
|
|
| 502 |
|
| 503 |
db = require_db_manager()
|
| 504 |
ip = _get_client_ip(request)
|
| 505 |
-
|
| 506 |
-
if guest_count >= config.GUEST_IP_DAILY_LIMIT:
|
| 507 |
-
raise HTTPException(
|
| 508 |
-
status_code=429,
|
| 509 |
-
detail="Too many guest sessions from this IP. Please create an account.",
|
| 510 |
-
)
|
| 511 |
-
user_id = db.create_guest_user(ip)
|
| 512 |
db.log_guest_ip(ip)
|
| 513 |
access_token = create_access_token(
|
| 514 |
data={"user_id": user_id, "is_guest": True},
|
| 515 |
-
expires_delta=datetime.timedelta(
|
| 516 |
)
|
| 517 |
-
return TokenResponse(access_token=access_token)
|
| 518 |
|
| 519 |
|
| 520 |
@app.post("/auth/convert", response_model=TokenResponse)
|
|
|
|
| 117 |
class TokenResponse(BaseModel):
|
| 118 |
access_token: str
|
| 119 |
token_type: str = "bearer"
|
| 120 |
+
user_id: Optional[int] = None
|
| 121 |
|
| 122 |
|
| 123 |
class ChatMessage(BaseModel):
|
|
|
|
| 503 |
|
| 504 |
db = require_db_manager()
|
| 505 |
ip = _get_client_ip(request)
|
| 506 |
+
user_id = db.get_or_create_guest_user(ip)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
db.log_guest_ip(ip)
|
| 508 |
access_token = create_access_token(
|
| 509 |
data={"user_id": user_id, "is_guest": True},
|
| 510 |
+
expires_delta=datetime.timedelta(days=7),
|
| 511 |
)
|
| 512 |
+
return TokenResponse(access_token=access_token, user_id=user_id)
|
| 513 |
|
| 514 |
|
| 515 |
@app.post("/auth/convert", response_model=TokenResponse)
|
frontend/app.js
CHANGED
|
@@ -6,7 +6,8 @@
|
|
| 6 |
const API = "https://tgrumb-michel.hf.space";
|
| 7 |
|
| 8 |
const MONTAIGNE_AVATAR = `<img src="montaigne-portrait.jpg" alt="M">`;
|
| 9 |
-
const INTRO_TITLE = "Conversations with Montaigne
|
|
|
|
| 10 |
const INTRO_COPY = "Bring a question, a worry, or a thought you want to turn over slowly. Montaigne replies in the spirit of the essays: curious, candid, and attentive to the shape of a life.";
|
| 11 |
|
| 12 |
const CONVERSATION_STARTERS = [
|
|
@@ -75,6 +76,7 @@ function clearSession() {
|
|
| 75 |
clearToken();
|
| 76 |
localStorage.removeItem("username");
|
| 77 |
localStorage.removeItem("is_guest");
|
|
|
|
| 78 |
}
|
| 79 |
|
| 80 |
function getDailyQuote() {
|
|
@@ -250,6 +252,7 @@ if (onChatPage) {
|
|
| 250 |
const data = JSON.parse(raw);
|
| 251 |
setToken(data.access_token);
|
| 252 |
localStorage.setItem("is_guest", "true");
|
|
|
|
| 253 |
localStorage.removeItem("username");
|
| 254 |
updateSidebarUser();
|
| 255 |
return true;
|
|
@@ -574,11 +577,12 @@ if (onChatPage) {
|
|
| 574 |
intro.innerHTML = `
|
| 575 |
<div class="chat-intro-frame">
|
| 576 |
<img src="montaigne-portrait.jpg" alt="Montaigne" class="chat-intro-portrait">
|
| 577 |
-
<div class="chat-intro-copy">
|
| 578 |
-
<p class="chat-intro-kicker">Enter the study</p>
|
| 579 |
-
<h2>${INTRO_TITLE}</h2>
|
| 580 |
-
<p class="chat-intro-
|
| 581 |
-
<
|
|
|
|
| 582 |
<p class="chat-intro-quote-text">“${quote.text}”</p>
|
| 583 |
<p class="chat-intro-quote-source">${quote.source}</p>
|
| 584 |
</div>
|
|
@@ -625,44 +629,65 @@ if (onChatPage) {
|
|
| 625 |
container.className = "starters-container";
|
| 626 |
container.id = "prompt-suggestions";
|
| 627 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
const grid = document.createElement("div");
|
| 629 |
grid.className = "starters-grid";
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
const
|
| 633 |
-
|
| 634 |
-
card.
|
| 635 |
-
card.
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
sendMessage(starter.text);
|
| 640 |
});
|
| 641 |
grid.appendChild(card);
|
| 642 |
-
}
|
| 643 |
-
container.appendChild(grid);
|
| 644 |
|
| 645 |
const divider = document.createElement("div");
|
| 646 |
divider.className = "starters-divider";
|
| 647 |
-
container.appendChild(divider);
|
| 648 |
|
| 649 |
const topicsRow = document.createElement("div");
|
| 650 |
-
topicsRow.className = "topics-row";
|
| 651 |
|
| 652 |
-
|
| 653 |
-
picks.forEach(idx => {
|
| 654 |
-
const topic = TOPIC_PATHS[idx];
|
| 655 |
const chip = document.createElement("button");
|
| 656 |
chip.className = "topic-chip";
|
| 657 |
chip.textContent = topic.label;
|
| 658 |
chip.addEventListener("click", () => {
|
| 659 |
container.remove();
|
| 660 |
-
document.getElementById("chat-intro")?.remove();
|
| 661 |
sendMessage(topic.prompt);
|
| 662 |
});
|
| 663 |
topicsRow.appendChild(chip);
|
| 664 |
});
|
| 665 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
messagesEl.appendChild(container);
|
| 667 |
scrollToBottom();
|
| 668 |
}
|
|
@@ -1239,9 +1264,9 @@ if (onChatPage) {
|
|
| 1239 |
});
|
| 1240 |
});
|
| 1241 |
|
| 1242 |
-
document.querySelector(".welcome-skip")?.addEventListener("click", () => {
|
| 1243 |
-
hideWelcomeModal();
|
| 1244 |
-
addWelcomeMessage({ showHero: false, showStarters: false });
|
| 1245 |
msgInput.focus();
|
| 1246 |
});
|
| 1247 |
|
|
|
|
| 6 |
const API = "https://tgrumb-michel.hf.space";
|
| 7 |
|
| 8 |
const MONTAIGNE_AVATAR = `<img src="montaigne-portrait.jpg" alt="M">`;
|
| 9 |
+
const INTRO_TITLE = "Conversations with Montaigne";
|
| 10 |
+
const INTRO_SUBTITLE = "Philosopher · Humanist · Friend";
|
| 11 |
const INTRO_COPY = "Bring a question, a worry, or a thought you want to turn over slowly. Montaigne replies in the spirit of the essays: curious, candid, and attentive to the shape of a life.";
|
| 12 |
|
| 13 |
const CONVERSATION_STARTERS = [
|
|
|
|
| 76 |
clearToken();
|
| 77 |
localStorage.removeItem("username");
|
| 78 |
localStorage.removeItem("is_guest");
|
| 79 |
+
localStorage.removeItem("guest_user_id");
|
| 80 |
}
|
| 81 |
|
| 82 |
function getDailyQuote() {
|
|
|
|
| 252 |
const data = JSON.parse(raw);
|
| 253 |
setToken(data.access_token);
|
| 254 |
localStorage.setItem("is_guest", "true");
|
| 255 |
+
if (data.user_id) localStorage.setItem("guest_user_id", String(data.user_id));
|
| 256 |
localStorage.removeItem("username");
|
| 257 |
updateSidebarUser();
|
| 258 |
return true;
|
|
|
|
| 577 |
intro.innerHTML = `
|
| 578 |
<div class="chat-intro-frame">
|
| 579 |
<img src="montaigne-portrait.jpg" alt="Montaigne" class="chat-intro-portrait">
|
| 580 |
+
<div class="chat-intro-copy">
|
| 581 |
+
<p class="chat-intro-kicker">Enter the study</p>
|
| 582 |
+
<h2>${INTRO_TITLE}</h2>
|
| 583 |
+
<p class="chat-intro-subtitle">${INTRO_SUBTITLE}</p>
|
| 584 |
+
<p class="chat-intro-text">${INTRO_COPY}</p>
|
| 585 |
+
<div class="chat-intro-quote">
|
| 586 |
<p class="chat-intro-quote-text">“${quote.text}”</p>
|
| 587 |
<p class="chat-intro-quote-source">${quote.source}</p>
|
| 588 |
</div>
|
|
|
|
| 629 |
container.className = "starters-container";
|
| 630 |
container.id = "prompt-suggestions";
|
| 631 |
|
| 632 |
+
const startersSection = document.createElement("div");
|
| 633 |
+
startersSection.className = "starters-section";
|
| 634 |
+
|
| 635 |
+
const startersToggle = document.createElement("button");
|
| 636 |
+
startersToggle.className = "topics-toggle starters-toggle";
|
| 637 |
+
startersToggle.type = "button";
|
| 638 |
+
startersToggle.innerHTML = '<span class="topics-toggle-label">Browse conversation starters</span><span class="topics-toggle-icon">▾</span>';
|
| 639 |
+
startersToggle.setAttribute("aria-expanded", "false");
|
| 640 |
+
startersSection.appendChild(startersToggle);
|
| 641 |
+
|
| 642 |
+
const startersPanel = document.createElement("div");
|
| 643 |
+
startersPanel.className = "starters-panel";
|
| 644 |
+
startersPanel.hidden = true;
|
| 645 |
+
|
| 646 |
const grid = document.createElement("div");
|
| 647 |
grid.className = "starters-grid";
|
| 648 |
+
|
| 649 |
+
CONVERSATION_STARTERS.forEach(starter => {
|
| 650 |
+
const card = document.createElement("button");
|
| 651 |
+
card.className = "starter-card";
|
| 652 |
+
card.innerHTML = `<span class="category">${starter.category}</span><span class="prompt">${starter.text}</span>`;
|
| 653 |
+
card.addEventListener("click", () => {
|
| 654 |
+
container.remove();
|
| 655 |
+
document.getElementById("chat-intro")?.remove();
|
| 656 |
+
sendMessage(starter.text);
|
|
|
|
| 657 |
});
|
| 658 |
grid.appendChild(card);
|
| 659 |
+
});
|
|
|
|
| 660 |
|
| 661 |
const divider = document.createElement("div");
|
| 662 |
divider.className = "starters-divider";
|
|
|
|
| 663 |
|
| 664 |
const topicsRow = document.createElement("div");
|
| 665 |
+
topicsRow.className = "topics-row topics-row--open";
|
| 666 |
|
| 667 |
+
TOPIC_PATHS.forEach(topic => {
|
|
|
|
|
|
|
| 668 |
const chip = document.createElement("button");
|
| 669 |
chip.className = "topic-chip";
|
| 670 |
chip.textContent = topic.label;
|
| 671 |
chip.addEventListener("click", () => {
|
| 672 |
container.remove();
|
| 673 |
+
document.getElementById("chat-intro")?.remove();
|
| 674 |
sendMessage(topic.prompt);
|
| 675 |
});
|
| 676 |
topicsRow.appendChild(chip);
|
| 677 |
});
|
| 678 |
+
|
| 679 |
+
startersPanel.appendChild(grid);
|
| 680 |
+
startersPanel.appendChild(divider);
|
| 681 |
+
startersPanel.appendChild(topicsRow);
|
| 682 |
+
startersSection.appendChild(startersPanel);
|
| 683 |
+
container.appendChild(startersSection);
|
| 684 |
+
|
| 685 |
+
startersToggle.addEventListener("click", () => {
|
| 686 |
+
const expanded = startersToggle.getAttribute("aria-expanded") === "true";
|
| 687 |
+
startersToggle.setAttribute("aria-expanded", String(!expanded));
|
| 688 |
+
startersPanel.hidden = expanded;
|
| 689 |
+
});
|
| 690 |
+
|
| 691 |
messagesEl.appendChild(container);
|
| 692 |
scrollToBottom();
|
| 693 |
}
|
|
|
|
| 1264 |
});
|
| 1265 |
});
|
| 1266 |
|
| 1267 |
+
document.querySelector(".welcome-skip")?.addEventListener("click", () => {
|
| 1268 |
+
hideWelcomeModal();
|
| 1269 |
+
addWelcomeMessage({ showHero: false, showStarters: false });
|
| 1270 |
msgInput.focus();
|
| 1271 |
});
|
| 1272 |
|
test_conversation_save.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Standalone Playwright test for conversation persistence.
|
| 3 |
+
|
| 4 |
+
Tests:
|
| 5 |
+
1. Registered user: send a message → reload → conversation persists in sidebar
|
| 6 |
+
2. Guest user: send a message → reload → conversation persists in sidebar
|
| 7 |
+
|
| 8 |
+
Usage:
|
| 9 |
+
pip install playwright
|
| 10 |
+
playwright install chromium
|
| 11 |
+
python test_conversation_save.py
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
import json
|
| 17 |
+
import urllib.request
|
| 18 |
+
import urllib.error
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
from playwright.sync_api import sync_playwright
|
| 22 |
+
except ImportError:
|
| 23 |
+
print("ERROR: playwright not installed. Run:")
|
| 24 |
+
print(" pip install playwright")
|
| 25 |
+
print(" playwright install chromium")
|
| 26 |
+
sys.exit(1)
|
| 27 |
+
|
| 28 |
+
API_BASE = "https://tgrumb-michel.hf.space"
|
| 29 |
+
FRONTEND_BASE = "https://ask-montaigne.pages.dev"
|
| 30 |
+
TEST_USER = "testbot"
|
| 31 |
+
TEST_PASS = "TestBot2026!"
|
| 32 |
+
TIMEOUT = 30_000
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _api(method, path, data=None, token=None):
|
| 36 |
+
url = f"{API_BASE}{path}"
|
| 37 |
+
body = json.dumps(data).encode() if data else None
|
| 38 |
+
headers = {"Content-Type": "application/json"}
|
| 39 |
+
if token:
|
| 40 |
+
headers["Authorization"] = f"Bearer {token}"
|
| 41 |
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
| 42 |
+
try:
|
| 43 |
+
resp = urllib.request.urlopen(req, timeout=15)
|
| 44 |
+
return resp.status, json.loads(resp.read())
|
| 45 |
+
except urllib.error.HTTPError as e:
|
| 46 |
+
return e.code, e.read().decode()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _register_test_user():
|
| 50 |
+
status, body = _api(
|
| 51 |
+
"POST", "/auth/register", {"username": TEST_USER, "password": TEST_PASS}
|
| 52 |
+
)
|
| 53 |
+
if status == 200:
|
| 54 |
+
print(f" Registered test user '{TEST_USER}'")
|
| 55 |
+
return body["access_token"]
|
| 56 |
+
if status == 400 and "already" in str(body).lower():
|
| 57 |
+
status2, body2 = _api(
|
| 58 |
+
"POST", "/auth/login", {"username": TEST_USER, "password": TEST_PASS}
|
| 59 |
+
)
|
| 60 |
+
if status2 == 200:
|
| 61 |
+
print(f" Test user '{TEST_USER}' already exists, logged in")
|
| 62 |
+
return body2["access_token"]
|
| 63 |
+
print(f" ERROR: login failed after registration conflict: {status2} {body2}")
|
| 64 |
+
return None
|
| 65 |
+
print(f" ERROR: registration failed: {status} {body}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _clean_test_conversations(token):
|
| 70 |
+
status, convos = _api("GET", "/chat/conversations", token=token)
|
| 71 |
+
if status != 200:
|
| 72 |
+
print(f" WARNING: could not list conversations: {status}")
|
| 73 |
+
return
|
| 74 |
+
for c in convos:
|
| 75 |
+
_api("DELETE", f"/chat/conversations/{c['id']}", token=token)
|
| 76 |
+
if convos:
|
| 77 |
+
print(f" Cleaned {len(convos)} existing conversations")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _print_result(name, passed, detail=""):
|
| 81 |
+
icon = "PASS" if passed else "FAIL"
|
| 82 |
+
print(f" [{icon}] {name}" + (f" — {detail}" if detail else ""))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_registered_user(p):
|
| 86 |
+
print("\n=== Test: Registered user conversation persistence ===")
|
| 87 |
+
token = _register_test_user()
|
| 88 |
+
if not token:
|
| 89 |
+
return False
|
| 90 |
+
_clean_test_conversations(token)
|
| 91 |
+
|
| 92 |
+
browser = p.chromium.launch(headless=True)
|
| 93 |
+
ctx = browser.new_context()
|
| 94 |
+
ctx.add_init_script("localStorage.setItem('welcome_shown', 'true');")
|
| 95 |
+
page = ctx.new_page()
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
page.goto(f"{FRONTEND_BASE}/chat.html", timeout=TIMEOUT)
|
| 99 |
+
page.wait_for_load_state("networkidle", timeout=TIMEOUT)
|
| 100 |
+
|
| 101 |
+
page.evaluate(
|
| 102 |
+
f"localStorage.setItem('token', '{token}');"
|
| 103 |
+
f" localStorage.setItem('username', '{TEST_USER}');"
|
| 104 |
+
f" localStorage.setItem('welcome_shown', 'true');"
|
| 105 |
+
)
|
| 106 |
+
page.reload(timeout=TIMEOUT)
|
| 107 |
+
page.wait_for_load_state("networkidle", timeout=TIMEOUT)
|
| 108 |
+
|
| 109 |
+
page.wait_for_selector("#chat-form", timeout=TIMEOUT)
|
| 110 |
+
time.sleep(1)
|
| 111 |
+
|
| 112 |
+
msg = "Hello Montaigne, this is a test of conversation persistence."
|
| 113 |
+
page.fill("#message-input", msg)
|
| 114 |
+
page.click("button.send-btn")
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
page.wait_for_selector(
|
| 118 |
+
"div.message.assistant:not(.thinking)",
|
| 119 |
+
timeout=60_000,
|
| 120 |
+
)
|
| 121 |
+
time.sleep(3)
|
| 122 |
+
except Exception:
|
| 123 |
+
_print_result(
|
| 124 |
+
"Assistant response appeared", False, "timeout waiting for reply"
|
| 125 |
+
)
|
| 126 |
+
browser.close()
|
| 127 |
+
return False
|
| 128 |
+
|
| 129 |
+
_print_result("Message sent and reply received", True)
|
| 130 |
+
|
| 131 |
+
page.reload(timeout=TIMEOUT)
|
| 132 |
+
page.wait_for_load_state("networkidle", timeout=TIMEOUT)
|
| 133 |
+
page.wait_for_selector("#conversations-list", timeout=TIMEOUT)
|
| 134 |
+
time.sleep(2)
|
| 135 |
+
|
| 136 |
+
sidebar_html = page.inner_html("#conversations-list")
|
| 137 |
+
has_convo = bool(sidebar_html.strip()) and "<" in sidebar_html
|
| 138 |
+
_print_result("Conversation appears in sidebar after reload", has_convo)
|
| 139 |
+
|
| 140 |
+
if has_convo:
|
| 141 |
+
convo_items = page.query_selector_all("#conversations-list > *")
|
| 142 |
+
_print_result(
|
| 143 |
+
"Sidebar has at least 1 conversation item",
|
| 144 |
+
len(convo_items) >= 1,
|
| 145 |
+
f"found {len(convo_items)}",
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
page.click("#conversations-list > *:first-child")
|
| 149 |
+
time.sleep(2)
|
| 150 |
+
|
| 151 |
+
chat_html = page.inner_html("#chat-messages")
|
| 152 |
+
msg_persisted = (
|
| 153 |
+
msg[:30] in chat_html or "test of conversation persistence" in chat_html
|
| 154 |
+
)
|
| 155 |
+
_print_result(
|
| 156 |
+
"Original message visible after clicking conversation", msg_persisted
|
| 157 |
+
)
|
| 158 |
+
else:
|
| 159 |
+
msg_persisted = False
|
| 160 |
+
|
| 161 |
+
browser.close()
|
| 162 |
+
return has_convo and msg_persisted
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
_print_result("Registered user test", False, str(e))
|
| 166 |
+
browser.close()
|
| 167 |
+
return False
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def test_guest_user(p):
|
| 171 |
+
print("\n=== Test: Guest user conversation persistence ===")
|
| 172 |
+
|
| 173 |
+
browser = p.chromium.launch(headless=True)
|
| 174 |
+
ctx = browser.new_context()
|
| 175 |
+
ctx.add_init_script("localStorage.setItem('welcome_shown', 'true');")
|
| 176 |
+
page = ctx.new_page()
|
| 177 |
+
|
| 178 |
+
try:
|
| 179 |
+
page.goto(f"{FRONTEND_BASE}/chat.html", timeout=TIMEOUT)
|
| 180 |
+
page.wait_for_load_state("networkidle", timeout=TIMEOUT)
|
| 181 |
+
page.wait_for_selector("#chat-form", timeout=TIMEOUT)
|
| 182 |
+
time.sleep(1)
|
| 183 |
+
|
| 184 |
+
msg = "Guest test: does my conversation survive a reload?"
|
| 185 |
+
page.fill("#message-input", msg)
|
| 186 |
+
page.click("button.send-btn")
|
| 187 |
+
|
| 188 |
+
try:
|
| 189 |
+
page.wait_for_selector(
|
| 190 |
+
"div.message.assistant:not(.thinking)",
|
| 191 |
+
timeout=60_000,
|
| 192 |
+
)
|
| 193 |
+
time.sleep(3)
|
| 194 |
+
except Exception:
|
| 195 |
+
_print_result("Assistant response appeared (guest)", False, "timeout")
|
| 196 |
+
browser.close()
|
| 197 |
+
return False
|
| 198 |
+
|
| 199 |
+
_print_result("Guest message sent and reply received", True)
|
| 200 |
+
|
| 201 |
+
guest_token = page.evaluate("localStorage.getItem('token')")
|
| 202 |
+
guest_username = page.evaluate("localStorage.getItem('username')")
|
| 203 |
+
print(f" Guest token present: {bool(guest_token)}, username: {guest_username}")
|
| 204 |
+
|
| 205 |
+
page.reload(timeout=TIMEOUT)
|
| 206 |
+
page.wait_for_load_state("networkidle", timeout=TIMEOUT)
|
| 207 |
+
page.wait_for_selector("#conversations-list", timeout=TIMEOUT)
|
| 208 |
+
time.sleep(2)
|
| 209 |
+
|
| 210 |
+
sidebar_html = page.inner_html("#conversations-list")
|
| 211 |
+
has_convo = bool(sidebar_html.strip()) and "<" in sidebar_html
|
| 212 |
+
_print_result("Guest conversation appears in sidebar after reload", has_convo)
|
| 213 |
+
|
| 214 |
+
if has_convo:
|
| 215 |
+
chat_html = page.inner_html("#chat-messages")
|
| 216 |
+
msg_persisted = (
|
| 217 |
+
"Guest test" in chat_html or "does my conversation survive" in chat_html
|
| 218 |
+
)
|
| 219 |
+
_print_result("Guest message visible after reload", msg_persisted)
|
| 220 |
+
else:
|
| 221 |
+
msg_persisted = False
|
| 222 |
+
_print_result(
|
| 223 |
+
"Guest message visible after reload",
|
| 224 |
+
False,
|
| 225 |
+
"no conversation in sidebar",
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
browser.close()
|
| 229 |
+
return has_convo and msg_persisted
|
| 230 |
+
|
| 231 |
+
except Exception as e:
|
| 232 |
+
_print_result("Guest user test", False, str(e))
|
| 233 |
+
browser.close()
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def main():
|
| 238 |
+
print(f"API: {API_BASE}")
|
| 239 |
+
print(f"Frontend: {FRONTEND_BASE}")
|
| 240 |
+
status, _ = _api("GET", "/health")
|
| 241 |
+
if status != 200:
|
| 242 |
+
print(f"ERROR: server not reachable (health={status})")
|
| 243 |
+
sys.exit(1)
|
| 244 |
+
print(f"Server health: OK")
|
| 245 |
+
|
| 246 |
+
with sync_playwright() as p:
|
| 247 |
+
reg_ok = test_registered_user(p)
|
| 248 |
+
guest_ok = test_guest_user(p)
|
| 249 |
+
|
| 250 |
+
print("\n=== Summary ===")
|
| 251 |
+
print(f" Registered user: {'PASS' if reg_ok else 'FAIL'}")
|
| 252 |
+
print(f" Guest user: {'PASS' if guest_ok else 'FAIL'}")
|
| 253 |
+
|
| 254 |
+
if not (reg_ok and guest_ok):
|
| 255 |
+
sys.exit(1)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
main()
|