security
This commit is contained in:
+127
-41
@@ -1,28 +1,28 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
extract::{Path, State, Form},
|
extract::{ConnectInfo, Form, Path, State},
|
||||||
response::Html,
|
response::Html,
|
||||||
};
|
};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use std::sync::Arc;
|
use std::{net::SocketAddr, sync::Arc};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
models::{ChatSession, Message, MessageSender, SendMessageForm, NewSessionForm, SessionStatus},
|
models::{ChatSession, Message, MessageSender, NewSessionForm, SendMessageForm, SessionStatus},
|
||||||
state::AppState,
|
state::{AppState, MESSAGE_LIMIT_PER_WINDOW, SESSION_LIMIT_PER_WINDOW},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MAX_MESSAGE_CHARS: usize = 1_000;
|
||||||
|
const MAX_NAME_CHARS: usize = 40;
|
||||||
|
|
||||||
fn render_message(msg: &Message) -> String {
|
fn render_message(msg: &Message) -> String {
|
||||||
let (bubble_class, label) = match msg.sender {
|
let (bubble_class, label) = match msg.sender {
|
||||||
MessageSender::Customer => ("msg-customer", "You"),
|
MessageSender::User => ("msg-user", "You"),
|
||||||
MessageSender::Agent => ("msg-agent", "Support"),
|
MessageSender::Supporter => ("msg-supporter", "Support"),
|
||||||
MessageSender::System => ("msg-system", ""),
|
MessageSender::System => ("msg-system", ""),
|
||||||
};
|
};
|
||||||
|
|
||||||
if msg.sender == MessageSender::System {
|
if msg.sender == MessageSender::System {
|
||||||
format!(
|
render_system_notice(&msg.content)
|
||||||
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
|
|
||||||
html_escape(&msg.content)
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
let time = msg.timestamp.format("%H:%M").to_string();
|
let time = msg.timestamp.format("%H:%M").to_string();
|
||||||
format!(
|
format!(
|
||||||
@@ -39,11 +39,34 @@ fn render_message(msg: &Message) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn render_system_notice(content: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"<div class=\"msg-system-wrap\"><span class=\"msg-system-text\">{}</span></div>",
|
||||||
|
html_escape(content)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
fn html_escape(s: &str) -> String {
|
fn html_escape(s: &str) -> String {
|
||||||
s.replace('&', "&")
|
s.replace('&', "&")
|
||||||
.replace('<', "<")
|
.replace('<', "<")
|
||||||
.replace('>', ">")
|
.replace('>', ">")
|
||||||
.replace('"', """)
|
.replace('"', """)
|
||||||
|
.replace('\'', "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn limit_key(kind: &str, addr: SocketAddr) -> String {
|
||||||
|
format!("{}:{}", kind, addr.ip())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clean_text(input: &str, max_chars: usize) -> Result<String, String> {
|
||||||
|
let trimmed = input.trim();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Ok(String::new());
|
||||||
|
}
|
||||||
|
if trimmed.chars().count() > max_chars {
|
||||||
|
return Err(format!("Please keep this under {max_chars} characters."));
|
||||||
|
}
|
||||||
|
Ok(trimmed.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /messages/:session_id
|
/// GET /messages/:session_id
|
||||||
@@ -52,76 +75,119 @@ pub async fn get_messages(
|
|||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
) -> Html<String> {
|
) -> Html<String> {
|
||||||
let Some(session) = state.sessions.get(&session_id) else {
|
let Some(session) = state.sessions.get(&session_id) else {
|
||||||
return Html("<p class='error'>Session not found.</p>".to_string());
|
return Html(render_system_notice(
|
||||||
|
"Session not found. Chat history may have been cleared; please start a new chat.",
|
||||||
|
));
|
||||||
};
|
};
|
||||||
let html: String = session.messages.iter().map(render_message).collect();
|
let html: String = session.messages.iter().map(render_message).collect();
|
||||||
Html(html)
|
Html(html)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /send/:session_id — customer sends a message
|
/// POST /send/:session_id — user sends a message
|
||||||
pub async fn send_message(
|
pub async fn send_message(
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
Path(session_id): Path<String>,
|
Path(session_id): Path<String>,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
Form(form): Form<SendMessageForm>,
|
Form(form): Form<SendMessageForm>,
|
||||||
) -> Html<String> {
|
) -> Html<String> {
|
||||||
let content = form.content.trim().to_string();
|
if state.is_rate_limited(limit_key("message", addr), MESSAGE_LIMIT_PER_WINDOW) {
|
||||||
|
return Html(render_system_notice(
|
||||||
|
"Too many messages from this network. Please wait until the 3-minute window resets.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = match clean_text(&form.content, MAX_MESSAGE_CHARS) {
|
||||||
|
Ok(content) => content,
|
||||||
|
Err(message) => return Html(render_system_notice(&message)),
|
||||||
|
};
|
||||||
if content.is_empty() {
|
if content.is_empty() {
|
||||||
return Html(String::new());
|
return Html(String::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let Some(mut session) = state.sessions.get_mut(&session_id) else {
|
||||||
|
return Html(render_system_notice(
|
||||||
|
"Session not found. Chat history may have been cleared; please start a new chat.",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
let msg = Message {
|
let msg = Message {
|
||||||
id: Uuid::new_v4().to_string(),
|
id: Uuid::new_v4().to_string(),
|
||||||
session_id: session_id.clone(),
|
session_id: session_id.clone(),
|
||||||
sender: MessageSender::Customer,
|
sender: MessageSender::User,
|
||||||
content,
|
content,
|
||||||
timestamp: Utc::now(),
|
timestamp: Utc::now(),
|
||||||
};
|
};
|
||||||
let rendered = render_message(&msg);
|
let rendered = render_message(&msg);
|
||||||
if let Some(mut session) = state.sessions.get_mut(&session_id) {
|
|
||||||
session.messages.push(msg);
|
session.messages.push(msg);
|
||||||
|
|
||||||
if let Some(tx) = state.notifiers.get(&session_id) {
|
if let Some(tx) = state.notifiers.get(&session_id) {
|
||||||
let _ = tx.send(session_id.clone());
|
let _ = tx.send(session_id.clone());
|
||||||
}
|
}
|
||||||
let _ = state.agent_notifier.send(session_id.clone());
|
let _ = state.supporter_notifier.send(session_id.clone());
|
||||||
}
|
|
||||||
Html(rendered)
|
Html(rendered)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /agent/send/:session_id — agent sends a message
|
/// POST /supporter/send/:session_id — supporter sends a message
|
||||||
pub async fn agent_send_message(
|
pub async fn supporter_send_message(
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
Path(session_id): Path<String>,
|
Path(session_id): Path<String>,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
Form(form): Form<SendMessageForm>,
|
Form(form): Form<SendMessageForm>,
|
||||||
) -> Html<String> {
|
) -> Html<String> {
|
||||||
let content = form.content.trim().to_string();
|
if state.is_rate_limited(limit_key("supporter-message", addr), MESSAGE_LIMIT_PER_WINDOW) {
|
||||||
|
return Html(render_system_notice(
|
||||||
|
"Too many messages from this network. Please wait until the 3-minute window resets.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let content = match clean_text(&form.content, MAX_MESSAGE_CHARS) {
|
||||||
|
Ok(content) => content,
|
||||||
|
Err(message) => return Html(render_system_notice(&message)),
|
||||||
|
};
|
||||||
if content.is_empty() {
|
if content.is_empty() {
|
||||||
return Html(String::new());
|
return Html(String::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let Some(mut session) = state.sessions.get_mut(&session_id) else {
|
||||||
|
return Html(render_system_notice(
|
||||||
|
"Session not found. Chat history may have been cleared.",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
let msg = Message {
|
let msg = Message {
|
||||||
id: Uuid::new_v4().to_string(),
|
id: Uuid::new_v4().to_string(),
|
||||||
session_id: session_id.clone(),
|
session_id: session_id.clone(),
|
||||||
sender: MessageSender::Agent,
|
sender: MessageSender::Supporter,
|
||||||
content,
|
content,
|
||||||
timestamp: Utc::now(),
|
timestamp: Utc::now(),
|
||||||
};
|
};
|
||||||
let rendered = render_message(&msg);
|
let rendered = render_message(&msg);
|
||||||
if let Some(mut session) = state.sessions.get_mut(&session_id) {
|
|
||||||
session.messages.push(msg);
|
session.messages.push(msg);
|
||||||
session.status = SessionStatus::Active;
|
session.status = SessionStatus::Active;
|
||||||
|
|
||||||
if let Some(tx) = state.notifiers.get(&session_id) {
|
if let Some(tx) = state.notifiers.get(&session_id) {
|
||||||
let _ = tx.send(session_id.clone());
|
let _ = tx.send(session_id.clone());
|
||||||
}
|
}
|
||||||
}
|
let _ = state.supporter_notifier.send(session_id.clone());
|
||||||
|
|
||||||
Html(rendered)
|
Html(rendered)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /sessions — session list for agent dashboard
|
/// GET /sessions — session list for supporter dashboard
|
||||||
pub async fn get_sessions(
|
pub async fn get_sessions(State(state): State<Arc<AppState>>) -> Html<String> {
|
||||||
State(state): State<Arc<AppState>>,
|
let mut sessions: Vec<_> = state
|
||||||
) -> Html<String> {
|
.sessions
|
||||||
let mut sessions: Vec<_> = state.sessions
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|s| s.status != SessionStatus::Closed)
|
.filter(|s| s.status != SessionStatus::Closed)
|
||||||
.map(|s| (s.id.clone(), s.customer_name.clone(), s.status.clone(), s.messages.len()))
|
.map(|s| {
|
||||||
|
(
|
||||||
|
s.id.clone(),
|
||||||
|
s.user_name.clone(),
|
||||||
|
s.status.clone(),
|
||||||
|
s.messages.len(),
|
||||||
|
)
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
sessions.sort_by(|a, b| a.0.cmp(&b.0));
|
sessions.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
@@ -147,9 +213,11 @@ pub async fn get_sessions(
|
|||||||
html.push_str(&format!(
|
html.push_str(&format!(
|
||||||
"<button class=\"session-item\" \
|
"<button class=\"session-item\" \
|
||||||
hx-get=\"/messages/{id}\" \
|
hx-get=\"/messages/{id}\" \
|
||||||
hx-target=\"#agent-messages\" \
|
hx-target=\"#supporter-messages\" \
|
||||||
hx-swap=\"innerHTML\" \
|
hx-swap=\"innerHTML\" \
|
||||||
onclick=\"document.querySelectorAll('.session-item').forEach(function(b){{b.classList.remove('selected')}}); this.classList.add('selected'); setActiveSession('{id}', '{escaped_name}')\">\
|
data-session-id=\"{id}\" \
|
||||||
|
data-session-name=\"{escaped_name}\" \
|
||||||
|
onclick=\"selectSession(this)\">\
|
||||||
<span class=\"session-name\">{escaped_name}</span>\
|
<span class=\"session-name\">{escaped_name}</span>\
|
||||||
<span class=\"session-meta\">\
|
<span class=\"session-meta\">\
|
||||||
<span class=\"session-badge {status_class}\">{status_label}</span>\
|
<span class=\"session-badge {status_class}\">{status_label}</span>\
|
||||||
@@ -162,43 +230,61 @@ pub async fn get_sessions(
|
|||||||
Html(html)
|
Html(html)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// POST /sessions/new — start a new customer session
|
/// POST /sessions/new — start a new user session
|
||||||
pub async fn new_session(
|
pub async fn new_session(
|
||||||
|
ConnectInfo(addr): ConnectInfo<SocketAddr>,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
Form(form): Form<NewSessionForm>,
|
Form(form): Form<NewSessionForm>,
|
||||||
) -> Html<String> {
|
) -> Html<String> {
|
||||||
let name = form.name.trim().to_string();
|
if state.is_rate_limited(limit_key("session", addr), SESSION_LIMIT_PER_WINDOW) {
|
||||||
let name = if name.is_empty() { "Anonymous".to_string() } else { name };
|
return Html(
|
||||||
|
"<script>alert('Too many new chats from this network. Please wait until the 3-minute window resets.');</script>"
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = match clean_text(&form.name, MAX_NAME_CHARS) {
|
||||||
|
Ok(name) if !name.is_empty() => name,
|
||||||
|
Ok(_) => "Anonymous".to_string(),
|
||||||
|
Err(message) => {
|
||||||
|
return Html(format!(
|
||||||
|
"<script>alert('{}');</script>",
|
||||||
|
html_escape(&message)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let session_id = Uuid::new_v4().to_string();
|
let session_id = Uuid::new_v4().to_string();
|
||||||
let short = session_id[..8].to_string();
|
let short = session_id[..8].to_string();
|
||||||
|
|
||||||
let session = ChatSession::new(session_id.clone(), name.clone());
|
let session = ChatSession::new(session_id.clone(), name.clone());
|
||||||
state.sessions.insert(session_id.clone(), session);
|
state.sessions.insert(session_id.clone(), session);
|
||||||
state.get_or_create_notifier(&session_id);
|
state.get_or_create_notifier(&session_id);
|
||||||
let _ = state.agent_notifier.send(session_id.clone());
|
let _ = state.supporter_notifier.send(session_id.clone());
|
||||||
|
|
||||||
// The response swaps out #start-form and fills #chat-container via OOB
|
// The response swaps out #start-form and fills #chat-container via OOB.
|
||||||
let html = format!(
|
let html = format!(
|
||||||
"<div id=\"chat-container\" style=\"display:flex;flex-direction:column\" hx-swap-oob=\"true\">\
|
"<div id=\"chat-container\" style=\"display:flex;flex-direction:column\" hx-swap-oob=\"true\">\
|
||||||
<div id=\"chat-header\">\
|
<div id=\"chat-header\">\
|
||||||
<span class=\"chat-status-dot active\"></span>\
|
<span>Support chat</span>\
|
||||||
<span>Support Chat</span>\
|
|
||||||
<span class=\"chat-session-id\">Session #{short}</span>\
|
<span class=\"chat-session-id\">Session #{short}</span>\
|
||||||
</div>\
|
</div>\
|
||||||
<div id=\"messages\" \
|
<div id=\"messages\" \
|
||||||
hx-get=\"/messages/{session_id}\" \
|
hx-get=\"/messages/{session_id}\" \
|
||||||
hx-trigger=\"load, every 2s\" \
|
hx-trigger=\"load, refresh, every 2s\" \
|
||||||
hx-swap=\"innerHTML\">\
|
hx-swap=\"innerHTML\">\
|
||||||
</div>\
|
</div>\
|
||||||
<div id=\"typing-indicator\" class=\"htmx-indicator\">\
|
<div id=\"peer-typing\" class=\"typing-bubble\" aria-live=\"polite\">\
|
||||||
|
<span class=\"typing-bubble-inner\" aria-label=\"Supporter is typing\">\
|
||||||
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
|
<span class=\"typing-dot\"></span><span class=\"typing-dot\"></span><span class=\"typing-dot\"></span>\
|
||||||
|
</span>\
|
||||||
</div>\
|
</div>\
|
||||||
<form id=\"chat-form\" \
|
<form id=\"chat-form\" \
|
||||||
hx-post=\"/send/{session_id}\" \
|
hx-post=\"/send/{session_id}\" \
|
||||||
hx-target=\"#messages\" \
|
hx-target=\"#messages\" \
|
||||||
hx-swap=\"beforeend\" \
|
hx-swap=\"beforeend\" \
|
||||||
hx-on=\"htmx:afterRequest: this.reset(); scrollMessages()\">\
|
hx-on=\"htmx:afterRequest: this.reset(); scrollMessages()\">\
|
||||||
<input type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" required />\
|
<input id=\"chat-input\" type=\"text\" name=\"content\" placeholder=\"Type your message...\" autocomplete=\"off\" maxlength=\"1000\" oninput=\"sendUserTyping()\" required />\
|
||||||
<button type=\"submit\">Send</button>\
|
<button type=\"submit\">Send</button>\
|
||||||
</form>\
|
</form>\
|
||||||
</div>\
|
</div>\
|
||||||
|
|||||||
+17
-5
@@ -1,9 +1,21 @@
|
|||||||
use axum::response::Html;
|
use axum::{extract::State, response::Html};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
pub async fn customer_page() -> Html<&'static str> {
|
use crate::state::AppState;
|
||||||
Html(include_str!("../../templates/customer.html"))
|
|
||||||
|
pub async fn index_page() -> Html<&'static str> {
|
||||||
|
Html(include_str!("../../templates/index.html"))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn agent_page() -> Html<&'static str> {
|
pub async fn user_page() -> Html<&'static str> {
|
||||||
Html(include_str!("../../templates/agent.html"))
|
Html(include_str!("../../templates/user.html"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn supporter_page() -> Html<&'static str> {
|
||||||
|
Html(include_str!("../../templates/supporter.html"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reset_countdown(State(state): State<Arc<AppState>>) -> Html<String> {
|
||||||
|
let seconds = state.reset_seconds_remaining();
|
||||||
|
Html(format!("Reset in {:02}:{:02}", seconds / 60, seconds % 60))
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-17
@@ -7,35 +7,44 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::state::AppState;
|
use crate::state::{AppState, RESET_EVENT};
|
||||||
|
|
||||||
/// WebSocket for customer — pushes notifications when agent replies
|
const USER_TYPING_PREFIX: &str = "typing:user:";
|
||||||
pub async fn customer_ws(
|
const SUPPORTER_TYPING_PREFIX: &str = "typing:supporter:";
|
||||||
|
|
||||||
|
/// WebSocket for user — pushes notifications when supporter replies
|
||||||
|
pub async fn user_ws(
|
||||||
ws: WebSocketUpgrade,
|
ws: WebSocketUpgrade,
|
||||||
Path(session_id): Path<String>,
|
Path(session_id): Path<String>,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
ws.on_upgrade(move |socket| handle_customer_socket(socket, session_id, state))
|
ws.on_upgrade(move |socket| handle_user_socket(socket, session_id, state))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_customer_socket(mut socket: WebSocket, session_id: String, state: Arc<AppState>) {
|
async fn handle_user_socket(mut socket: WebSocket, session_id: String, state: Arc<AppState>) {
|
||||||
let tx = state.get_or_create_notifier(&session_id);
|
let tx = state.get_or_create_notifier(&session_id);
|
||||||
let mut rx = tx.subscribe();
|
let mut rx = tx.subscribe();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
// Forward broadcast events to the customer browser
|
// Forward broadcast events to the user browser.
|
||||||
Ok(sid) = rx.recv() => {
|
Ok(sid) = rx.recv() => {
|
||||||
if sid == session_id {
|
if sid == session_id || sid == RESET_EVENT || sid.starts_with(SUPPORTER_TYPING_PREFIX) || sid.starts_with(USER_TYPING_PREFIX) {
|
||||||
// Signal HTMX to re-poll messages
|
if socket.send(Message::Text(sid)).await.is_err() {
|
||||||
if socket.send(Message::Text("refresh".into())).await.is_err() {
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Handle ping/close from client
|
// Handle ping/close and typing events from client.
|
||||||
msg = socket.recv() => {
|
msg = socket.recv() => {
|
||||||
match msg {
|
match msg {
|
||||||
|
Some(Ok(Message::Text(text))) => {
|
||||||
|
let expected = format!("{USER_TYPING_PREFIX}{session_id}");
|
||||||
|
if text == expected {
|
||||||
|
let _ = tx.send(text.clone());
|
||||||
|
let _ = state.supporter_notifier.send(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some(Ok(Message::Close(_))) | None => break,
|
Some(Ok(Message::Close(_))) | None => break,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
@@ -44,27 +53,35 @@ async fn handle_customer_socket(mut socket: WebSocket, session_id: String, state
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// WebSocket for agent dashboard — pushes notifications when any session updates
|
/// WebSocket for supporter dashboard — pushes notifications when any session updates
|
||||||
pub async fn agent_ws(
|
pub async fn supporter_ws(
|
||||||
ws: WebSocketUpgrade,
|
ws: WebSocketUpgrade,
|
||||||
Path(_agent_id): Path<String>,
|
Path(_supporter_id): Path<String>,
|
||||||
State(state): State<Arc<AppState>>,
|
State(state): State<Arc<AppState>>,
|
||||||
) -> impl IntoResponse {
|
) -> impl IntoResponse {
|
||||||
ws.on_upgrade(move |socket| handle_agent_socket(socket, state))
|
ws.on_upgrade(move |socket| handle_supporter_socket(socket, state))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_agent_socket(mut socket: WebSocket, state: Arc<AppState>) {
|
async fn handle_supporter_socket(mut socket: WebSocket, state: Arc<AppState>) {
|
||||||
let mut rx = state.agent_notifier.subscribe();
|
let mut rx = state.supporter_notifier.subscribe();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
Ok(session_id) = rx.recv() => {
|
Ok(session_id) = rx.recv() => {
|
||||||
if socket.send(Message::Text(session_id.into())).await.is_err() {
|
if socket.send(Message::Text(session_id)).await.is_err() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
msg = socket.recv() => {
|
msg = socket.recv() => {
|
||||||
match msg {
|
match msg {
|
||||||
|
Some(Ok(Message::Text(text))) => {
|
||||||
|
if let Some(session_id) = text.strip_prefix(SUPPORTER_TYPING_PREFIX) {
|
||||||
|
if !session_id.is_empty() && state.sessions.contains_key(session_id) {
|
||||||
|
let tx = state.get_or_create_notifier(session_id);
|
||||||
|
let _ = tx.send(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some(Ok(Message::Close(_))) | None => break,
|
Some(Ok(Message::Close(_))) | None => break,
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
+20
-9
@@ -6,11 +6,11 @@ use axum::{
|
|||||||
Router,
|
Router,
|
||||||
routing::{get, post},
|
routing::{get, post},
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::{net::SocketAddr, sync::Arc};
|
||||||
use tower_http::services::ServeDir;
|
use tower_http::services::ServeDir;
|
||||||
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
use state::AppState;
|
use state::{AppState, CHAT_RESET_INTERVAL};
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
@@ -23,16 +23,27 @@ async fn main() {
|
|||||||
|
|
||||||
let state = Arc::new(AppState::new());
|
let state = Arc::new(AppState::new());
|
||||||
|
|
||||||
|
let reset_state = state.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(CHAT_RESET_INTERVAL).await;
|
||||||
|
reset_state.clear_everything();
|
||||||
|
tracing::info!("Cleared all in-memory chat sessions, messages, notifiers, and rate limits");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/", get(handlers::pages::customer_page))
|
.route("/", get(handlers::pages::index_page))
|
||||||
.route("/agent", get(handlers::pages::agent_page))
|
.route("/user", get(handlers::pages::user_page))
|
||||||
.route("/ws/customer/:session_id", get(handlers::ws::customer_ws))
|
.route("/supporter", get(handlers::pages::supporter_page))
|
||||||
.route("/ws/agent/:agent_id", get(handlers::ws::agent_ws))
|
.route("/reset-countdown", get(handlers::pages::reset_countdown))
|
||||||
|
.route("/ws/user/:session_id", get(handlers::ws::user_ws))
|
||||||
|
.route("/ws/supporter/:supporter_id", get(handlers::ws::supporter_ws))
|
||||||
.route("/messages/:session_id", get(handlers::chat::get_messages))
|
.route("/messages/:session_id", get(handlers::chat::get_messages))
|
||||||
.route("/send/:session_id", post(handlers::chat::send_message))
|
.route("/send/:session_id", post(handlers::chat::send_message))
|
||||||
.route(
|
.route(
|
||||||
"/agent/send/:session_id",
|
"/supporter/send/:session_id",
|
||||||
post(handlers::chat::agent_send_message),
|
post(handlers::chat::supporter_send_message),
|
||||||
)
|
)
|
||||||
.route("/sessions", get(handlers::chat::get_sessions))
|
.route("/sessions", get(handlers::chat::get_sessions))
|
||||||
.route("/sessions/new", post(handlers::chat::new_session))
|
.route("/sessions/new", post(handlers::chat::new_session))
|
||||||
@@ -43,7 +54,7 @@ async fn main() {
|
|||||||
tracing::info!("Chat service running — http://0.0.0.0:3111");
|
tracing::info!("Chat service running — http://0.0.0.0:3111");
|
||||||
axum::Server::from_tcp(listener.into_std().unwrap())
|
axum::Server::from_tcp(listener.into_std().unwrap())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.serve(app.into_make_service())
|
.serve(app.into_make_service_with_connect_info::<SocketAddr>())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-6
@@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize};
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
pub enum MessageSender {
|
pub enum MessageSender {
|
||||||
Customer,
|
User,
|
||||||
Agent,
|
Supporter,
|
||||||
System,
|
System,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,25 +29,25 @@ pub enum SessionStatus {
|
|||||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
pub struct ChatSession {
|
pub struct ChatSession {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub customer_name: String,
|
pub user_name: String,
|
||||||
pub status: SessionStatus,
|
pub status: SessionStatus,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub messages: Vec<Message>,
|
pub messages: Vec<Message>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChatSession {
|
impl ChatSession {
|
||||||
pub fn new(id: String, customer_name: String) -> Self {
|
pub fn new(id: String, user_name: String) -> Self {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let welcome = Message {
|
let welcome = Message {
|
||||||
id: uuid::Uuid::new_v4().to_string(),
|
id: uuid::Uuid::new_v4().to_string(),
|
||||||
session_id: id.clone(),
|
session_id: id.clone(),
|
||||||
sender: MessageSender::System,
|
sender: MessageSender::System,
|
||||||
content: "Welcome! A support agent will be with you shortly.".to_string(),
|
content: "Welcome! A supporter will be with you shortly.".to_string(),
|
||||||
timestamp: now,
|
timestamp: now,
|
||||||
};
|
};
|
||||||
Self {
|
Self {
|
||||||
id,
|
id,
|
||||||
customer_name,
|
user_name,
|
||||||
status: SessionStatus::Waiting,
|
status: SessionStatus::Waiting,
|
||||||
created_at: now,
|
created_at: now,
|
||||||
messages: vec![welcome],
|
messages: vec![welcome],
|
||||||
|
|||||||
+66
-6
@@ -1,22 +1,40 @@
|
|||||||
use dashmap::DashMap;
|
|
||||||
use tokio::sync::broadcast;
|
|
||||||
use crate::models::ChatSession;
|
use crate::models::ChatSession;
|
||||||
|
use dashmap::DashMap;
|
||||||
|
use std::{sync::Mutex, time::{Duration, Instant}};
|
||||||
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
|
pub const RESET_EVENT: &str = "__reset__";
|
||||||
|
pub const CHAT_RESET_INTERVAL: Duration = Duration::from_secs(3 * 60);
|
||||||
|
pub const RATE_LIMIT_WINDOW: Duration = CHAT_RESET_INTERVAL;
|
||||||
|
pub const MESSAGE_LIMIT_PER_WINDOW: u32 = 60;
|
||||||
|
pub const SESSION_LIMIT_PER_WINDOW: u32 = 10;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct RateLimitEntry {
|
||||||
|
window_started: Instant,
|
||||||
|
count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub sessions: DashMap<String, ChatSession>,
|
pub sessions: DashMap<String, ChatSession>,
|
||||||
// broadcast channel: session_id -> sender
|
// broadcast channel: session_id -> sender
|
||||||
pub notifiers: DashMap<String, broadcast::Sender<String>>,
|
pub notifiers: DashMap<String, broadcast::Sender<String>>,
|
||||||
// agent broadcast for new sessions
|
// supporter broadcast for new sessions and updates
|
||||||
pub agent_notifier: broadcast::Sender<String>,
|
pub supporter_notifier: broadcast::Sender<String>,
|
||||||
|
// in-memory rate limits, wiped with all other state every three minutes
|
||||||
|
pub rate_limits: DashMap<String, RateLimitEntry>,
|
||||||
|
reset_started: Mutex<Instant>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let (agent_tx, _) = broadcast::channel(64);
|
let (supporter_tx, _) = broadcast::channel(64);
|
||||||
Self {
|
Self {
|
||||||
sessions: DashMap::new(),
|
sessions: DashMap::new(),
|
||||||
notifiers: DashMap::new(),
|
notifiers: DashMap::new(),
|
||||||
agent_notifier: agent_tx,
|
supporter_notifier: supporter_tx,
|
||||||
|
rate_limits: DashMap::new(),
|
||||||
|
reset_started: Mutex::new(Instant::now()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,4 +47,46 @@ impl AppState {
|
|||||||
tx
|
tx
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_rate_limited(&self, key: String, limit: u32) -> bool {
|
||||||
|
let now = Instant::now();
|
||||||
|
let mut entry = self.rate_limits.entry(key).or_insert(RateLimitEntry {
|
||||||
|
window_started: now,
|
||||||
|
count: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
if now.duration_since(entry.window_started) >= RATE_LIMIT_WINDOW {
|
||||||
|
entry.window_started = now;
|
||||||
|
entry.count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
entry.count += 1;
|
||||||
|
entry.count > limit
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset_seconds_remaining(&self) -> u64 {
|
||||||
|
let elapsed = self
|
||||||
|
.reset_started
|
||||||
|
.lock()
|
||||||
|
.map(|started| started.elapsed())
|
||||||
|
.unwrap_or(Duration::ZERO);
|
||||||
|
|
||||||
|
CHAT_RESET_INTERVAL.saturating_sub(elapsed).as_secs()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_everything(&self) {
|
||||||
|
for tx in self.notifiers.iter() {
|
||||||
|
let _ = tx.value().send(RESET_EVENT.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.sessions.clear();
|
||||||
|
self.notifiers.clear();
|
||||||
|
self.rate_limits.clear();
|
||||||
|
|
||||||
|
if let Ok(mut reset_started) = self.reset_started.lock() {
|
||||||
|
*reset_started = Instant::now();
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = self.supporter_notifier.send(RESET_EVENT.to_string());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Support Chat</title>
|
||||||
|
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
|
||||||
|
<style>
|
||||||
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #111318;
|
||||||
|
--surface: #191c22;
|
||||||
|
--surface-soft: #20242c;
|
||||||
|
--border: #2b303a;
|
||||||
|
--accent: #8f9cff;
|
||||||
|
--text: #eceff4;
|
||||||
|
--muted: #9aa3b2;
|
||||||
|
--radius: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
min-height: 100vh;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card {
|
||||||
|
width: min(560px, 100%);
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 22px;
|
||||||
|
padding: 2rem;
|
||||||
|
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.25);
|
||||||
|
}
|
||||||
|
|
||||||
|
.timer {
|
||||||
|
display: inline-flex;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--muted);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.35rem 0.75rem;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
background: var(--bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: clamp(1.6rem, 4vw, 2.15rem);
|
||||||
|
letter-spacing: -0.035em;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.6;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.choices {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.35rem;
|
||||||
|
text-decoration: none;
|
||||||
|
color: var(--text);
|
||||||
|
background: var(--surface-soft);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 1.1rem;
|
||||||
|
transition: transform 0.15s, border-color 0.15s, background 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
transform: translateY(-1px);
|
||||||
|
border-color: var(--accent);
|
||||||
|
background: #242936;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-title { font-weight: 700; font-size: 1rem; }
|
||||||
|
.role-detail { color: var(--muted); font-size: 0.88rem; }
|
||||||
|
|
||||||
|
@media (max-width: 560px) {
|
||||||
|
.choices { grid-template-columns: 1fr; }
|
||||||
|
.card { padding: 1.5rem; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="card">
|
||||||
|
<span class="timer" hx-get="/reset-countdown" hx-trigger="load, every 1s" hx-swap="innerHTML">Reset in --:--</span>
|
||||||
|
<h1>Support chat</h1>
|
||||||
|
<p>Open the side you want to test. Each option opens in a new tab.</p>
|
||||||
|
|
||||||
|
<div class="choices">
|
||||||
|
<a href="/user" target="_blank" rel="noopener noreferrer">
|
||||||
|
<span class="role-title">User</span>
|
||||||
|
<span class="role-detail">Start a new conversation</span>
|
||||||
|
</a>
|
||||||
|
<a href="/supporter" target="_blank" rel="noopener noreferrer">
|
||||||
|
<span class="role-title">Supporter</span>
|
||||||
|
<span class="role-detail">View and reply to conversations</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,487 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Support Dashboard</title>
|
||||||
|
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
|
||||||
|
<style>
|
||||||
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #111318;
|
||||||
|
--surface: #191c22;
|
||||||
|
--surface2: #20242c;
|
||||||
|
--border: #2b303a;
|
||||||
|
--accent: #8f9cff;
|
||||||
|
--accent-dim: #737fd3;
|
||||||
|
--text: #eceff4;
|
||||||
|
--muted: #9aa3b2;
|
||||||
|
--user: #8f9cff;
|
||||||
|
--supporter: #2b303a;
|
||||||
|
--radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
background: var(--bg);
|
||||||
|
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
color: var(--text);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.layout {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 280px 1fr;
|
||||||
|
grid-template-rows: 56px 1fr;
|
||||||
|
height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar h1 {
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.topbar-timer {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
color: var(--muted);
|
||||||
|
background: var(--bg);
|
||||||
|
padding: 0.25rem 0.65rem;
|
||||||
|
border-radius: 20px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar {
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-header {
|
||||||
|
padding: 1rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#session-list {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 0.5rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#session-list::-webkit-scrollbar { width: 4px; }
|
||||||
|
#session-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
|
||||||
|
|
||||||
|
.session-item {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 0.7rem 0.8rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 0.88rem;
|
||||||
|
transition: background 0.15s, border-color 0.15s;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.3rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-item:hover { background: var(--surface2); border-color: var(--border); }
|
||||||
|
.session-item.selected { background: var(--surface2); border-color: var(--accent); }
|
||||||
|
|
||||||
|
.session-name { font-weight: 700; }
|
||||||
|
|
||||||
|
.session-meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.session-badge {
|
||||||
|
font-size: 0.68rem;
|
||||||
|
padding: 0.15rem 0.5rem;
|
||||||
|
border-radius: 20px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-waiting { background: rgba(220, 173, 43, 0.15); color: #dcad2b; }
|
||||||
|
.status-active { background: rgba(143, 156, 255, 0.16); color: var(--accent); }
|
||||||
|
.status-closed { background: rgba(154, 163, 178, 0.12); color: var(--muted); }
|
||||||
|
|
||||||
|
.session-count { font-size: 0.75rem; color: var(--muted); }
|
||||||
|
.session-id { font-size: 0.7rem; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
||||||
|
|
||||||
|
.no-sessions {
|
||||||
|
padding: 1.5rem 1rem;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--muted);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-panel {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main-header {
|
||||||
|
padding: 0.9rem 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
min-height: 56px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#active-session-name {
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#active-session-meta {
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#supporter-messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 1.2rem 1.5rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
#supporter-messages::-webkit-scrollbar { width: 4px; }
|
||||||
|
#supporter-messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
color: var(--muted);
|
||||||
|
gap: 0.5rem;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-wrap { display: flex; }
|
||||||
|
.msg-user-wrap { justify-content: flex-end; }
|
||||||
|
.msg-supporter-wrap { justify-content: flex-start; }
|
||||||
|
|
||||||
|
.msg-user, .msg-supporter {
|
||||||
|
max-width: 65%;
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-user {
|
||||||
|
background: var(--user);
|
||||||
|
color: #111318;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-supporter {
|
||||||
|
background: var(--supporter);
|
||||||
|
color: var(--text);
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 600;
|
||||||
|
opacity: 0.7;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-text { margin: 0; }
|
||||||
|
|
||||||
|
.msg-time {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.68rem;
|
||||||
|
opacity: 0.55;
|
||||||
|
margin-top: 4px;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-system-wrap { display: flex; justify-content: center; margin: 0.25rem 0; }
|
||||||
|
.msg-system-text {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--muted);
|
||||||
|
background: var(--bg);
|
||||||
|
padding: 0.25rem 0.75rem;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-bubble {
|
||||||
|
display: none;
|
||||||
|
padding: 0 1.5rem 0.55rem;
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-bubble.visible { display: flex; }
|
||||||
|
|
||||||
|
.typing-bubble-inner {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 48px;
|
||||||
|
padding: 0.65rem 0.85rem;
|
||||||
|
background: var(--supporter);
|
||||||
|
border-radius: 16px;
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-dot {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--muted);
|
||||||
|
animation: typing-bounce 1.1s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-dot:nth-child(2) { animation-delay: 0.16s; }
|
||||||
|
.typing-dot:nth-child(3) { animation-delay: 0.32s; }
|
||||||
|
|
||||||
|
@keyframes typing-bounce {
|
||||||
|
0%, 75%, 100% { transform: translateY(0); opacity: 0.45; }
|
||||||
|
35% { transform: translateY(-5px); opacity: 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
#reply-area {
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
#reply-area.visible { display: flex; gap: 0.6rem; }
|
||||||
|
|
||||||
|
#reply-area input[type="text"] {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.65rem 1rem;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#reply-area input[type="text"]:focus { border-color: var(--accent); }
|
||||||
|
|
||||||
|
#reply-area button {
|
||||||
|
padding: 0.65rem 1.2rem;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #111318;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#reply-area button:hover { background: var(--accent-dim); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="layout">
|
||||||
|
<header class="topbar">
|
||||||
|
<h1>Support dashboard</h1>
|
||||||
|
<span class="topbar-timer" hx-get="/reset-countdown" hx-trigger="load, every 1s" hx-swap="innerHTML">Reset in --:--</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<aside class="sidebar">
|
||||||
|
<div class="sidebar-header">Conversations</div>
|
||||||
|
<div id="session-list"
|
||||||
|
hx-get="/sessions"
|
||||||
|
hx-trigger="load, refresh, every 5s"
|
||||||
|
hx-swap="innerHTML">
|
||||||
|
<p class="no-sessions">Loading...</p>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="main-panel">
|
||||||
|
<div class="main-header">
|
||||||
|
<span id="active-session-name" style="color: var(--muted)">Select a conversation</span>
|
||||||
|
<span id="active-session-meta"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="supporter-messages">
|
||||||
|
<div class="empty-state">
|
||||||
|
<p>No conversation selected</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="supporter-peer-typing" class="typing-bubble" aria-live="polite">
|
||||||
|
<span class="typing-bubble-inner" aria-label="User is typing">
|
||||||
|
<span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="reply-area">
|
||||||
|
<input type="text" id="reply-input" placeholder="Reply to user..." autocomplete="off" maxlength="1000" />
|
||||||
|
<button id="reply-btn">Send</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let activeSessionId = null;
|
||||||
|
let supporterWs = null;
|
||||||
|
let typingHideTimer = null;
|
||||||
|
let lastTypingSent = 0;
|
||||||
|
|
||||||
|
function selectSession(button) {
|
||||||
|
document.querySelectorAll('.session-item').forEach(function(b) { b.classList.remove('selected'); });
|
||||||
|
button.classList.add('selected');
|
||||||
|
setActiveSession(button.dataset.sessionId, button.dataset.sessionName);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setActiveSession(sessionId, name) {
|
||||||
|
activeSessionId = sessionId;
|
||||||
|
document.getElementById('active-session-name').textContent = name;
|
||||||
|
document.getElementById('active-session-meta').textContent = '#' + sessionId.slice(0, 8);
|
||||||
|
document.getElementById('reply-area').classList.add('visible');
|
||||||
|
hideUserTyping();
|
||||||
|
scrollSupporterMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetSupporterDashboard() {
|
||||||
|
activeSessionId = null;
|
||||||
|
document.getElementById('active-session-name').textContent = 'Select a conversation';
|
||||||
|
document.getElementById('active-session-meta').textContent = '';
|
||||||
|
document.getElementById('reply-area').classList.remove('visible');
|
||||||
|
hideUserTyping();
|
||||||
|
document.getElementById('supporter-messages').innerHTML = '<div class="empty-state"><p>Chat history was cleared. New conversations will appear here.</p></div>';
|
||||||
|
htmx.trigger('#session-list', 'refresh');
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollSupporterMessages() {
|
||||||
|
const el = document.getElementById('supporter-messages');
|
||||||
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showUserTyping() {
|
||||||
|
const indicator = document.getElementById('supporter-peer-typing');
|
||||||
|
if (!indicator) return;
|
||||||
|
indicator.classList.add('visible');
|
||||||
|
clearTimeout(typingHideTimer);
|
||||||
|
typingHideTimer = setTimeout(hideUserTyping, 1400);
|
||||||
|
scrollSupporterMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function hideUserTyping() {
|
||||||
|
const indicator = document.getElementById('supporter-peer-typing');
|
||||||
|
if (indicator) indicator.classList.remove('visible');
|
||||||
|
clearTimeout(typingHideTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendSupporterTyping() {
|
||||||
|
if (!activeSessionId || !supporterWs || supporterWs.readyState !== WebSocket.OPEN) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastTypingSent < 500) return;
|
||||||
|
lastTypingSent = now;
|
||||||
|
supporterWs.send(`typing:supporter:${activeSessionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('htmx:afterSwap', (e) => {
|
||||||
|
if (e.detail.target.id === 'supporter-messages') scrollSupporterMessages();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('reply-btn').addEventListener('click', () => {
|
||||||
|
if (!activeSessionId) return;
|
||||||
|
const input = document.getElementById('reply-input');
|
||||||
|
const content = input.value.trim();
|
||||||
|
if (!content) return;
|
||||||
|
|
||||||
|
fetch(`/supporter/send/${activeSessionId}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: `content=${encodeURIComponent(content)}`
|
||||||
|
})
|
||||||
|
.then(r => r.text())
|
||||||
|
.then(html => {
|
||||||
|
const msgs = document.getElementById('supporter-messages');
|
||||||
|
msgs.insertAdjacentHTML('beforeend', html);
|
||||||
|
scrollSupporterMessages();
|
||||||
|
input.value = '';
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('reply-input').addEventListener('keydown', (e) => {
|
||||||
|
if (e.key === 'Enter') document.getElementById('reply-btn').click();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('reply-input').addEventListener('input', sendSupporterTyping);
|
||||||
|
|
||||||
|
function connectSupporterWS() {
|
||||||
|
const wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||||
|
supporterWs = new WebSocket(`${wsProtocol}://${location.host}/ws/supporter/dashboard`);
|
||||||
|
|
||||||
|
supporterWs.onmessage = (e) => {
|
||||||
|
const data = e.data;
|
||||||
|
if (data === '__reset__') {
|
||||||
|
resetSupporterDashboard();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.startsWith('typing:user:')) {
|
||||||
|
const sessionId = data.replace('typing:user:', '');
|
||||||
|
if (sessionId === activeSessionId) showUserTyping();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.startsWith('typing:supporter:')) return;
|
||||||
|
|
||||||
|
htmx.trigger('#session-list', 'refresh');
|
||||||
|
|
||||||
|
if (data === activeSessionId) {
|
||||||
|
fetch(`/messages/${activeSessionId}`)
|
||||||
|
.then(r => r.text())
|
||||||
|
.then(html => {
|
||||||
|
document.getElementById('supporter-messages').innerHTML = html;
|
||||||
|
scrollSupporterMessages();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
supporterWs.onclose = () => setTimeout(connectSupporterWS, 2000);
|
||||||
|
}
|
||||||
|
|
||||||
|
connectSupporterWS();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Support Chat</title>
|
||||||
|
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
|
||||||
|
<style>
|
||||||
|
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #111318;
|
||||||
|
--surface: #191c22;
|
||||||
|
--surface-soft: #20242c;
|
||||||
|
--border: #2b303a;
|
||||||
|
--accent: #8f9cff;
|
||||||
|
--accent-dim: #737fd3;
|
||||||
|
--text: #eceff4;
|
||||||
|
--muted: #9aa3b2;
|
||||||
|
--user: #8f9cff;
|
||||||
|
--supporter: #2b303a;
|
||||||
|
--radius: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background: var(--bg);
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
color: var(--text);
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-timer {
|
||||||
|
position: fixed;
|
||||||
|
top: 1rem;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
color: var(--muted);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 0.35rem 0.75rem;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
background: var(--surface);
|
||||||
|
z-index: 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 20px;
|
||||||
|
padding: 2.2rem;
|
||||||
|
width: min(360px, 100%);
|
||||||
|
text-align: left;
|
||||||
|
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form h1 {
|
||||||
|
font-size: 1.35rem;
|
||||||
|
font-weight: 700;
|
||||||
|
margin-bottom: 0.45rem;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form p {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--muted);
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form input[type="text"] {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form input[type="text"]:focus { border-color: var(--accent); }
|
||||||
|
|
||||||
|
#start-form button {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.75rem;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #111318;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 700;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#start-form button:hover { background: var(--accent-dim); }
|
||||||
|
|
||||||
|
#chat-container {
|
||||||
|
display: none;
|
||||||
|
flex-direction: column;
|
||||||
|
width: min(390px, 100%);
|
||||||
|
height: min(600px, calc(100vh - 4.5rem));
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 20px;
|
||||||
|
overflow: hidden;
|
||||||
|
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.22);
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
padding: 1rem 1.2rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chat-session-id {
|
||||||
|
margin-left: auto;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
|
||||||
|
#messages {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 1rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
}
|
||||||
|
|
||||||
|
#messages::-webkit-scrollbar { width: 4px; }
|
||||||
|
#messages::-webkit-scrollbar-track { background: transparent; }
|
||||||
|
#messages::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
|
||||||
|
|
||||||
|
.msg-wrap { display: flex; }
|
||||||
|
.msg-user-wrap { justify-content: flex-end; }
|
||||||
|
.msg-supporter-wrap { justify-content: flex-start; }
|
||||||
|
|
||||||
|
.msg-user, .msg-supporter {
|
||||||
|
max-width: 75%;
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
border-radius: 16px;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-user {
|
||||||
|
background: var(--user);
|
||||||
|
color: #111318;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-supporter {
|
||||||
|
background: var(--supporter);
|
||||||
|
color: var(--text);
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
font-weight: 600;
|
||||||
|
opacity: 0.7;
|
||||||
|
margin-bottom: 2px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-text { margin: 0; }
|
||||||
|
|
||||||
|
.msg-time {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.68rem;
|
||||||
|
opacity: 0.55;
|
||||||
|
margin-top: 4px;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-system-wrap {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
margin: 0.25rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.msg-system-text {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--muted);
|
||||||
|
background: var(--bg);
|
||||||
|
padding: 0.25rem 0.75rem;
|
||||||
|
border-radius: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-bubble {
|
||||||
|
display: none;
|
||||||
|
padding: 0 1rem 0.55rem;
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-bubble.visible { display: flex; }
|
||||||
|
|
||||||
|
.typing-bubble-inner {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 48px;
|
||||||
|
padding: 0.65rem 0.85rem;
|
||||||
|
background: var(--supporter);
|
||||||
|
border-radius: 16px;
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-dot {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--muted);
|
||||||
|
animation: typing-bounce 1.1s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.typing-dot:nth-child(2) { animation-delay: 0.16s; }
|
||||||
|
.typing-dot:nth-child(3) { animation-delay: 0.32s; }
|
||||||
|
|
||||||
|
@keyframes typing-bounce {
|
||||||
|
0%, 75%, 100% { transform: translateY(0); opacity: 0.45; }
|
||||||
|
35% { transform: translateY(-5px); opacity: 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form input[type="text"] {
|
||||||
|
flex: 1;
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
background: var(--bg);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
color: var(--text);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form input[type="text"]:focus { border-color: var(--accent); }
|
||||||
|
|
||||||
|
#chat-form button {
|
||||||
|
padding: 0.6rem 1.1rem;
|
||||||
|
background: var(--accent);
|
||||||
|
color: #111318;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
font-weight: 700;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chat-form button:hover { background: var(--accent-dim); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<span class="page-timer" hx-get="/reset-countdown" hx-trigger="load, every 1s" hx-swap="innerHTML">Reset in --:--</span>
|
||||||
|
|
||||||
|
<div id="start-form">
|
||||||
|
<h1>Talk to support</h1>
|
||||||
|
<p>Start a conversation and a supporter can reply from the dashboard.</p>
|
||||||
|
<form hx-post="/sessions/new"
|
||||||
|
hx-target="body"
|
||||||
|
hx-swap="beforeend">
|
||||||
|
<input type="text" name="name" placeholder="Your name (optional)" maxlength="40" />
|
||||||
|
<button type="submit">Start chat</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="chat-container"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let ws = null;
|
||||||
|
let typingHideTimer = null;
|
||||||
|
let lastTypingSent = 0;
|
||||||
|
|
||||||
|
function scrollMessages() {
|
||||||
|
const el = document.getElementById('messages');
|
||||||
|
if (el) el.scrollTop = el.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSupporterTyping() {
|
||||||
|
const indicator = document.getElementById('peer-typing');
|
||||||
|
if (!indicator) return;
|
||||||
|
indicator.classList.add('visible');
|
||||||
|
clearTimeout(typingHideTimer);
|
||||||
|
typingHideTimer = setTimeout(() => indicator.classList.remove('visible'), 1400);
|
||||||
|
scrollMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendUserTyping() {
|
||||||
|
if (!ws || ws.readyState !== WebSocket.OPEN || !window.__sessionId) return;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - lastTypingSent < 500) return;
|
||||||
|
lastTypingSent = now;
|
||||||
|
ws.send(`typing:user:${window.__sessionId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('htmx:afterSwap', (e) => {
|
||||||
|
if (e.detail.target.id === 'messages') scrollMessages();
|
||||||
|
});
|
||||||
|
|
||||||
|
function resetChat() {
|
||||||
|
const oldWs = ws;
|
||||||
|
ws = null;
|
||||||
|
window.__sessionId = null;
|
||||||
|
if (oldWs) oldWs.close();
|
||||||
|
const startForm = document.getElementById('start-form');
|
||||||
|
const chatContainer = document.getElementById('chat-container');
|
||||||
|
startForm.style.display = 'block';
|
||||||
|
chatContainer.style.display = 'none';
|
||||||
|
chatContainer.innerHTML = '';
|
||||||
|
alert('Chat history was cleared. Please start a new chat.');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('htmx:afterRequest', (e) => {
|
||||||
|
if (e.detail.requestConfig?.path === '/sessions/new' && !ws) {
|
||||||
|
const container = document.getElementById('chat-container');
|
||||||
|
if (!container) return;
|
||||||
|
const match = container.innerHTML.match(/\/messages\/([a-f0-9-]+)/);
|
||||||
|
if (!match) return;
|
||||||
|
const sessionId = match[1];
|
||||||
|
window.__sessionId = sessionId;
|
||||||
|
|
||||||
|
const wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||||
|
ws = new WebSocket(`${wsProtocol}://${location.host}/ws/user/${sessionId}`);
|
||||||
|
ws.onmessage = (message) => {
|
||||||
|
if (message.data === '__reset__') {
|
||||||
|
resetChat();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (message.data.startsWith('typing:supporter:')) {
|
||||||
|
showSupporterTyping();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (message.data.startsWith('typing:user:')) return;
|
||||||
|
htmx.trigger('#messages', 'refresh');
|
||||||
|
};
|
||||||
|
ws.onerror = () => console.warn('WebSocket error; polling will continue.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user