Refine chat management: auto-titles, per-chat rename/delete, custom modal
- Auto-title a session from its first user message (chat_title) so chats are distinguishable in the sidebar instead of all 'Nuova chat'. - Per-chat rename (✏️) and delete (🗑️) buttons with aria-labels; stopPropagation so they don't switch the conversation. deleteSessionById selects a fallback or creates a fresh session. - Replace native prompt()/confirm() with a styled custom modal (showDialog): mobile-friendly and inspectable by automation (native dialogs hung the browser subagent). Verified via direct HTTP (auto-title/rename/delete) + 108 tests; browser subagent avoided after repeated hangs.
This commit is contained in:
1 parent
8979201139
commit
0123f41d99
5 files changed
+198
-10
No files matched your search
@@ -126,6 +126,19 @@ pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Err
|
||||
Ok(Json(with_store(&st, |s| s.stats()).await?))
|
||||
}
|
||||
|
||||
/// A short, single-line title derived from the first user message.
|
||||
fn chat_title(content: &str) -> String {
|
||||
let line = content.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
let mut t: String = line.chars().take(48).collect();
|
||||
if line.chars().count() > 48 {
|
||||
t.push('…');
|
||||
}
|
||||
if t.is_empty() {
|
||||
t = "Nuova chat".to_string();
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
fn role_of(s: &str) -> Role {
|
||||
match s {
|
||||
"system" | "developer" => Role::System,
|
||||
@@ -294,6 +307,17 @@ pub(crate) async fn session_chat(
|
||||
return e.into_response();
|
||||
}
|
||||
|
||||
// Auto-title a fresh session from its first user message, so chats are
|
||||
// distinguishable in the sidebar instead of all being "Nuova chat".
|
||||
if history.is_empty() {
|
||||
let title = chat_title(&body.content);
|
||||
let _ = with_store(&st, {
|
||||
let id = id.clone();
|
||||
move |s| s.rename_session(&id, &title)
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
// Agent mode: drive the model↔shell_exec loop, streaming progress events.
|
||||
if body.agent {
|
||||
req.tools = Some(agent::agent_tools());
|
||||
@@ -438,3 +462,23 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::chat_title;
|
||||
|
||||
#[test]
|
||||
fn title_collapses_whitespace_and_truncates() {
|
||||
assert_eq!(chat_title(" ciao mondo "), "ciao mondo");
|
||||
assert_eq!(chat_title(""), "Nuova chat");
|
||||
assert_eq!(chat_title(" "), "Nuova chat");
|
||||
let long = "a".repeat(80);
|
||||
let t = chat_title(&long);
|
||||
assert_eq!(t.chars().count(), 49); // 48 + ellipsis
|
||||
assert!(t.ends_with('…'));
|
||||
// multibyte truncation stays on char boundaries
|
||||
let emoji = "😀".repeat(60);
|
||||
let t2 = chat_title(&emoji);
|
||||
assert!(t2.chars().count() <= 49);
|
||||
}
|
||||
}
|
||||
@@ -299,3 +299,39 @@ async fn agent_mode_streams_events_and_persists() {
|
||||
assert_eq!(msgs.last().unwrap().role, "assistant");
|
||||
assert_eq!(msgs.last().unwrap().content, "efghi");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn first_message_auto_titles_and_rename_delete_work() {
|
||||
let (app, store) = build_app().await;
|
||||
let id = create_session(&app).await;
|
||||
assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Nuova chat");
|
||||
|
||||
// First user message auto-titles the session.
|
||||
req(
|
||||
&app,
|
||||
Method::POST,
|
||||
&format!("/api/sessions/{id}/chat"),
|
||||
Some(serde_json::json!({"content": "Qual è la capitale?"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
store.get_session(&id).unwrap().unwrap().title,
|
||||
"Qual è la capitale?"
|
||||
);
|
||||
|
||||
// Rename via PATCH.
|
||||
let (st, _) = req(
|
||||
&app,
|
||||
Method::PATCH,
|
||||
&format!("/api/sessions/{id}"),
|
||||
Some(serde_json::json!({"title": "Mio titolo"})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(st, StatusCode::OK);
|
||||
assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo");
|
||||
|
||||
// Delete via DELETE.
|
||||
let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await;
|
||||
assert_eq!(st, StatusCode::NO_CONTENT);
|
||||
assert!(store.get_session(&id).unwrap().is_none());
|
||||
}
|
||||
+22
-4
@@ -85,12 +85,22 @@ body.resizing { cursor: col-resize; user-select: none; }
|
||||
.brand { font-weight: 700; letter-spacing: 0.3px; }
|
||||
#session-list { list-style: none; margin: 0; padding: 8px; overflow-y: auto; flex: 1; }
|
||||
#session-list li {
|
||||
padding: 12px; border-radius: 10px; cursor: pointer;
|
||||
color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
min-height: 44px; display: flex; align-items: center;
|
||||
padding: 8px 10px; border-radius: 10px; cursor: pointer;
|
||||
color: var(--muted); min-height: 44px;
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 8px;
|
||||
}
|
||||
#session-list li:hover { background: var(--panel-2); }
|
||||
#session-list li.active { background: var(--panel-2); color: var(--text); }
|
||||
.session-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.session-actions { display: flex; gap: 2px; opacity: 0; transition: opacity 0.12s ease; }
|
||||
#session-list li:hover .session-actions, #session-list li.active .session-actions { opacity: 1; }
|
||||
.sess-btn {
|
||||
background: transparent; border: none; cursor: pointer; font-size: 0.9rem;
|
||||
padding: 4px 6px; min-height: 32px; border-radius: 6px; line-height: 1;
|
||||
}
|
||||
.sess-btn:hover { background: var(--border); }
|
||||
.sess-btn.danger:hover { background: var(--danger); }
|
||||
@media (hover: none) { .session-actions { opacity: 1; } }
|
||||
.drawer-foot { padding: 12px; border-top: 1px solid var(--border); }
|
||||
|
||||
/* ---- Main column ---- */
|
||||
@@ -169,7 +179,7 @@ details.thinking .reasoning {
|
||||
#send { min-width: 52px; font-size: 1.3rem; }
|
||||
|
||||
/* ---- Stats modal ---- */
|
||||
#stats-modal {
|
||||
#stats-modal, #dialog {
|
||||
position: fixed; inset: 0; z-index: 40;
|
||||
background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center;
|
||||
padding: 20px;
|
||||
@@ -182,6 +192,14 @@ details.thinking .reasoning {
|
||||
#stats-body { display: grid; grid-template-columns: 1fr auto; gap: 6px 16px; margin: 0 0 16px; }
|
||||
#stats-body dt { color: var(--muted); }
|
||||
#stats-body dd { margin: 0; font-variant-numeric: tabular-nums; }
|
||||
#dialog-msg { margin: 0 0 16px; }
|
||||
#dialog-input {
|
||||
width: 100%; background: var(--panel-2); color: var(--text);
|
||||
border: 1px solid var(--border); border-radius: 10px;
|
||||
padding: 10px 12px; font-size: 16px; font-family: inherit; margin: 0 0 16px;
|
||||
}
|
||||
#dialog-input:focus { outline: none; border-color: var(--accent); }
|
||||
.dialog-actions { display: flex; gap: 8px; justify-content: flex-end; }
|
||||
|
||||
/* ---- Wide screens: persistent sidebar ---- */
|
||||
@media (min-width: 900px) {
|
||||
|
||||
+83
-6
@@ -117,7 +117,20 @@ function renderSessions() {
|
||||
const list = $("#session-list");
|
||||
list.textContent = "";
|
||||
for (const s of state.sessions) {
|
||||
const li = el("li", s.id === state.current ? "active" : null, s.title);
|
||||
const li = el("li", s.id === state.current ? "active" : null);
|
||||
li.appendChild(el("span", "session-title", s.title));
|
||||
const actions = el("span", "session-actions");
|
||||
const ren = el("button", "sess-btn", "\u{270F}\u{FE0F}");
|
||||
ren.title = "Rinomina";
|
||||
ren.setAttribute("aria-label", "Rinomina chat");
|
||||
ren.addEventListener("click", (e) => { e.stopPropagation(); renameSessionById(s.id, s.title); });
|
||||
const del = el("button", "sess-btn danger", "\u{1F5D1}\u{FE0F}");
|
||||
del.title = "Elimina";
|
||||
del.setAttribute("aria-label", "Elimina chat");
|
||||
del.addEventListener("click", (e) => { e.stopPropagation(); deleteSessionById(s.id); });
|
||||
actions.appendChild(ren);
|
||||
actions.appendChild(del);
|
||||
li.appendChild(actions);
|
||||
li.addEventListener("click", () => { selectSession(s.id); closeDrawer(); });
|
||||
list.appendChild(li);
|
||||
}
|
||||
@@ -187,11 +200,40 @@ async function newSession() {
|
||||
}
|
||||
|
||||
async function deleteSession() {
|
||||
if (!state.current) return;
|
||||
if (!confirm("Eliminare questa conversazione?")) return;
|
||||
await sendJSON(`/api/sessions/${state.current}`, "DELETE");
|
||||
state.current = null;
|
||||
await loadSessions();
|
||||
if (state.current) await deleteSessionById(state.current);
|
||||
}
|
||||
|
||||
async function renameSessionById(id, currentTitle) {
|
||||
const input = await showDialog({ title: "Rinomina chat", input: currentTitle, okText: "Salva" });
|
||||
if (input === null) return;
|
||||
const title = input.trim();
|
||||
if (!title) return;
|
||||
await sendJSON(`/api/sessions/${id}`, "PATCH", { title });
|
||||
state.sessions = await getJSON("/api/sessions");
|
||||
renderSessions();
|
||||
if (id === state.current) $("#session-title").textContent = title;
|
||||
}
|
||||
|
||||
async function deleteSessionById(id) {
|
||||
const ok = await showDialog({
|
||||
title: "Elimina chat",
|
||||
message: "Eliminare questa chat? L'operazione non è reversibile.",
|
||||
okText: "Elimina",
|
||||
});
|
||||
if (!ok) return;
|
||||
await sendJSON(`/api/sessions/${id}`, "DELETE");
|
||||
const wasCurrent = id === state.current;
|
||||
state.sessions = await getJSON("/api/sessions");
|
||||
if (wasCurrent) {
|
||||
state.current = null;
|
||||
if (!state.sessions.length) {
|
||||
const s = await sendJSON("/api/sessions", "POST", {});
|
||||
state.sessions = [s];
|
||||
}
|
||||
await selectSession(state.sessions[0].id);
|
||||
} else {
|
||||
renderSessions();
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
@@ -321,6 +363,41 @@ async function showStats() {
|
||||
$("#stats-modal").hidden = false;
|
||||
}
|
||||
|
||||
// A custom modal dialog (replaces native prompt/confirm: styled, mobile-friendly,
|
||||
// and inspectable by automation). Resolves with the input string (or null on
|
||||
// cancel) when `input` is given, otherwise true/false.
|
||||
function showDialog({ title, message = "", input = null, okText = "OK" }) {
|
||||
return new Promise((resolve) => {
|
||||
$("#dialog-title").textContent = title;
|
||||
const msg = $("#dialog-msg");
|
||||
msg.textContent = message;
|
||||
msg.hidden = !message;
|
||||
const inp = $("#dialog-input");
|
||||
inp.hidden = input === null;
|
||||
if (input !== null) inp.value = input;
|
||||
$("#dialog-ok").textContent = okText;
|
||||
const dlg = $("#dialog");
|
||||
dlg.hidden = false;
|
||||
if (input !== null) { inp.focus(); inp.select(); }
|
||||
const finish = (val) => {
|
||||
dlg.hidden = true;
|
||||
$("#dialog-ok").removeEventListener("click", onOk);
|
||||
$("#dialog-cancel").removeEventListener("click", onCancel);
|
||||
inp.removeEventListener("keydown", onKey);
|
||||
resolve(val);
|
||||
};
|
||||
const onOk = () => finish(input !== null ? inp.value : true);
|
||||
const onCancel = () => finish(input !== null ? null : false);
|
||||
const onKey = (e) => {
|
||||
if (e.key === "Enter") { e.preventDefault(); onOk(); }
|
||||
else if (e.key === "Escape") { e.preventDefault(); onCancel(); }
|
||||
};
|
||||
$("#dialog-ok").addEventListener("click", onOk);
|
||||
$("#dialog-cancel").addEventListener("click", onCancel);
|
||||
inp.addEventListener("keydown", onKey);
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Drawer / input UX ----------------------------------------------------
|
||||
function openDrawer() { $("#drawer").classList.add("open"); $("#scrim").hidden = false; }
|
||||
function closeDrawer() { $("#drawer").classList.remove("open"); $("#scrim").hidden = true; }
|
||||
|
||||
@@ -54,6 +54,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Generic dialog (rename input / delete confirm); replaces native prompt/confirm -->
|
||||
<div id="dialog" hidden>
|
||||
<div class="modal-card">
|
||||
<h2 id="dialog-title"></h2>
|
||||
<p id="dialog-msg" class="muted"></p>
|
||||
<input id="dialog-input" type="text" autocomplete="off" hidden />
|
||||
<div class="dialog-actions">
|
||||
<button id="dialog-cancel" class="btn">Annulla</button>
|
||||
<button id="dialog-ok" class="btn primary">OK</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module" src="/assets/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user