Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(sessions): add recycle bin for deleted chats (#1398)

evan188199-tech9b066b5f98b3
diff --git a/deeptutor/api/routers/sessions.py b/deeptutor/api/routers/sessions.py
index dca444da7..c3306c03a 100644
--- a/deeptutor/api/routers/sessions.py
+++ b/deeptutor/api/routers/sessions.py
@@ -173,6 +173,16 @@ def _truncate_oversized_events(
event["_truncated"] = True
[email protected]("/recycle-bin")
+async def list_recycle_bin(
+ limit: int = Query(default=50, ge=1, le=200),
+ offset: int = Query(default=0, ge=0),
+):
+ store = get_session_store()
+ sessions = await store.list_deleted_sessions(limit=limit, offset=offset)
+ return {"sessions": sessions}
+
+
@router.get("/{session_id}")
async def get_session(session_id: str):
store = get_session_store()
@@ -282,9 +292,28 @@ async def delete_session(session_id: str):
runtime = get_turn_runtime_manager()
for turn in await list_active_turns(session_id):
await runtime.cancel_turn(turn["id"])
- deleted = await store.delete_session(session_id)
+ deleted = await store.soft_delete_session(session_id)
if not deleted:
raise HTTPException(status_code=404, detail="Session not found")
+ return {"deleted": True, "session_id": session_id, "recycled": True}
+
+
[email protected]("/{session_id}/restore")
+async def restore_session(session_id: str):
+ store = get_session_store()
+ restored = await store.restore_session(session_id)
+ if not restored:
+ raise HTTPException(status_code=404, detail="Session not found in recycle bin")
+ refreshed = await store.get_session(session_id)
+ return {"restored": True, "session": refreshed}
+
+
[email protected]("/{session_id}/purge")
+async def purge_session(session_id: str):
+ store = get_session_store()
+ purged = await store.hard_delete_session(session_id)
+ if not purged:
+ raise HTTPException(status_code=404, detail="Session not found in recycle bin")
try:
await asyncio.to_thread(LearningStore().detach_session, session_id)
except Exception:
@@ -293,7 +322,7 @@ async def delete_session(session_id: str):
await get_attachment_store().delete_session(session_id)
except Exception:
logger.exception("failed to clean up attachments for session %s", session_id)
- return {"deleted": True, "session_id": session_id}
+ return {"purged": True, "session_id": session_id}
@router.put("/{session_id}/branch-selection")
diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.py
index c86e34486..8eb7c6742 100644
--- a/deeptutor/services/session/pocketbase_store.py
+++ b/deeptutor/services/session/pocketbase_store.py
@@ -99,17 +99,30 @@ def _current_user_id() -> str:
return _validate_id(get_current_user().id, "user_id")
-def _find_session_record(pb: Any, session_id: str, user_id: str) -> Any | None:
+def _find_session_record(
+ pb: Any, session_id: str, user_id: str, *, recycled: bool | None = None
+) -> Any | None:
"""Return the ``sessions`` record for *session_id* owned by *user_id*.
Scoping every session lookup by ``user_id`` is the single point that keeps
one user from reading or mutating another's sessions on the shared
PocketBase backend. Returns ``None`` when no such row exists for this user.
+
+ ``recycled`` narrows the match by ``deleted_at`` — ``False`` requires an
+ active session, ``True`` requires one already in the recycle bin, and
+ ``None`` (the default) ignores the recycle-bin state entirely, preserving
+ lookup behaviour for callers that predate it. One column carries this:
+ a row is in the bin exactly when ``deleted_at`` is set.
"""
records = pb.collection("sessions").get_full_list(
query_params={"filter": f'session_id="{session_id}" && user_id="{user_id}"'}
)
- return records[0] if records else None
+ if not records:
+ return None
+ record = records[0]
+ if recycled is not None and bool(_to_float(getattr(record, "deleted_at", None))) != recycled:
+ return None
+ return record
class PocketBaseSessionStore:
@@ -213,7 +226,7 @@ class PocketBaseSessionStore:
def _get():
try:
- return _find_session_record(_pb(), sid, uid)
+ return _find_session_record(_pb(), sid, uid, recycled=False)
except Exception:
return None
@@ -254,6 +267,7 @@ class PocketBaseSessionStore:
or time.time()
)
preferences_raw = getattr(record, "preferences_json", None)
+ deleted_at_raw = getattr(record, "deleted_at", None)
return {
"id": sid,
"session_id": sid,
@@ -269,6 +283,8 @@ class PocketBaseSessionStore:
"capability": getattr(record, "capability", "") or "",
"status": getattr(record, "status", "idle") or "idle",
"active_turn_id": "",
+ "is_deleted": bool(_to_float(getattr(record, "deleted_at", None))),
+ "deleted_at": _to_float(deleted_at_raw) if deleted_at_raw not in (None, "") else None,
}
async def update_session_title(self, session_id: str, title: str) -> bool:
@@ -372,10 +388,16 @@ class PocketBaseSessionStore:
return await asyncio.to_thread(_import)
async def delete_session(self, session_id: str) -> bool:
+ """Remove a session outright, recycle bin or not.
+
+ The internal cleanups own this one — a reading workspace that is gone
+ takes its sessions with it, and those never belonged to the learner's
+ recycle bin. The chat surface calls :meth:`soft_delete_session`.
+ """
sid = _validate_id(session_id, "session_id")
uid = _current_user_id()
- def _delete():
+ def _do():
record = _find_session_record(_pb(), sid, uid)
if record is None:
return False
@@ -383,11 +405,95 @@ class PocketBaseSessionStore:
return True
try:
- return await asyncio.to_thread(_delete)
+ return await asyncio.to_thread(_do)
except Exception as exc:
logger.warning(f"delete_session failed: {exc}")
return False
+ async def soft_delete_session(self, session_id: str) -> bool:
+ """Move a session to the recycle bin (soft delete)."""
+ sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
+
+ def _do():
+ record = _find_session_record(_pb(), sid, uid, recycled=False)
+ if record is None:
+ return False
+ _pb().collection("sessions").update(record.id, {"deleted_at": time.time()})
+ return True
+
+ try:
+ return await asyncio.to_thread(_do)
+ except Exception as exc:
+ logger.warning(f"soft_delete_session failed: {exc}")
+ return False
+
+ async def restore_session(self, session_id: str) -> bool:
+ """Restore a soft-deleted session from the recycle bin."""
+ sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
+
+ def _do():
+ record = _find_session_record(_pb(), sid, uid, recycled=True)
+ if record is None:
+ return False
+ _pb().collection("sessions").update(record.id, {"deleted_at": None})
+ return True
+
+ try:
+ return await asyncio.to_thread(_do)
+ except Exception as exc:
+ logger.warning(f"restore_session failed: {exc}")
+ return False
+
+ async def hard_delete_session(self, session_id: str) -> bool:
+ """Permanently delete a session from the recycle bin.
+
+ Requires a prior soft-delete (defence-in-depth), matching the SQLite
+ backend's guard against accidentally skipping the recycle bin.
+ """
+ sid = _validate_id(session_id, "session_id")
+ uid = _current_user_id()
+
+ def _do():
+ record = _find_session_record(_pb(), sid, uid, recycled=True)
+ if record is None:
+ return False
+ _pb().collection("sessions").delete(record.id)
+ return True
+
+ try:
+ return await asyncio.to_thread(_do)
+ except Exception as exc:
+ logger.warning(f"hard_delete_session failed: {exc}")
+ return False
+
+ async def list_deleted_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:
+ """List soft-deleted sessions ordered by deletion time.
+
+ PocketBase filter strings can't be trusted across server versions for
+ boolean comparisons, so the soft-delete filter and the ``deleted_at``
+ ordering are both applied client-side after fetching the user's rows.
+ """
+ uid = _current_user_id()
+
+ def _do():
+ records = (
+ _pb()
+ .collection("sessions")
+ .get_full_list(query_params={"filter": f'user_id="{uid}"'})
+ )
+ deleted = [r for r in records if _to_float(getattr(r, "deleted_at", None))]
+ deleted.sort(key=lambda r: _to_float(getattr(r, "deleted_at", None)), reverse=True)
+ page = deleted[offset : offset + limit]
+ return [self._session_record_to_dict(r) for r in page]
+
+ try:
+ return await asyncio.to_thread(_do)
+ except Exception as exc:
+ logger.warning(f"list_deleted_sessions failed: {exc}")
+ return []
+
async def list_sessions(
self,
limit: int = 50,
@@ -399,7 +505,7 @@ class PocketBaseSessionStore:
def _list():
query_params: dict[str, Any] = {
"sort": "-session_updated_at",
- "filter": f'user_id="{uid}"',
+ "filter": f'user_id="{uid}" && deleted_at = null',
}
return _pb().collection("sessions").get_list(page, limit, query_params=query_params)
@@ -408,7 +514,15 @@ class PocketBaseSessionStore:
# Reading conversations are listed like any other: the sidebar
# groups them under their collection and a click returns to the
# reader. See the note on ``_WHERE_NATIVE`` in the SQLite store.
- return [self._session_record_to_dict(r) for r in result.items]
+ #
+ # The filter above excludes soft-deleted rows on real PocketBase
+ # servers; this is a defensive re-check for servers/mocks where
+ # boolean filter comparisons behave unexpectedly.
+ return [
+ self._session_record_to_dict(r)
+ for r in result.items
+ if not _to_float(getattr(r, "deleted_at", None))
+ ]
except Exception as exc:
logger.warning(f"list_sessions failed: {exc}")
return []
diff --git a/deeptutor/services/session/protocol.py b/deeptutor/services/session/protocol.py
index 732f361e5..e3cdbebcc 100644
--- a/deeptutor/services/session/protocol.py
+++ b/deeptutor/services/session/protocol.py
@@ -60,6 +60,16 @@ class SessionRepository(Protocol):
async def update_session_title(self, session_id: str, title: str) -> bool: ...
+ async def soft_delete_session(self, session_id: str) -> bool: ...
+
+ async def restore_session(self, session_id: str) -> bool: ...
+
+ async def hard_delete_session(self, session_id: str) -> bool: ...
+
+ async def list_deleted_sessions(
+ self, limit: int = 50, offset: int = 0
+ ) -> list[dict[str, Any]]: ...
+
async def delete_session(self, session_id: str) -> bool: ...
@@ -166,6 +176,16 @@ class SessionStoreProtocol(SessionRepository, TurnRepository, MessageRepository,
async def update_session_title(self, session_id: str, title: str) -> bool: ...
+ async def soft_delete_session(self, session_id: str) -> bool: ...
+
+ async def restore_session(self, session_id: str) -> bool: ...
+
+ async def hard_delete_session(self, session_id: str) -> bool: ...
+
+ async def list_deleted_sessions(
+ self, limit: int = 50, offset: int = 0
+ ) -> list[dict[str, Any]]: ...
+
async def delete_session(self, session_id: str) -> bool: ...
async def add_message(
diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.py
index c914eb4d9..5cbdb76cd 100644
--- a/deeptutor/services/session/sqlite_store.py
+++ b/deeptutor/services/session/sqlite_store.py
@@ -371,6 +371,8 @@ class SQLiteSessionStore:
columns = {row[1] for row in conn.execute("PRAGMA table_info(sessions)").fetchall()}
if "preferences_json" not in columns:
conn.execute("ALTER TABLE sessions ADD COLUMN preferences_json TEXT DEFAULT '{}'")
+ if "deleted_at" not in columns:
+ conn.execute("ALTER TABLE sessions ADD COLUMN deleted_at REAL DEFAULT NULL")
self._migrate_workspace_preferences(conn)
if "kind" in columns:
try:
@@ -1366,8 +1368,69 @@ class SQLiteSessionStore:
return cur.rowcount > 0
async def delete_session(self, session_id: str) -> bool:
+ """Remove a session outright, recycle bin or not.
+
+ The internal cleanups own this one: a reading workspace that is gone
+ takes its sessions with it, and those never belonged to the learner's
+ recycle bin — they would arrive there unasked and restore into a
+ workspace that no longer exists. The chat surface calls
+ :meth:`soft_delete_session` instead, which is the deletion a learner
+ performs and can undo.
+ """
return await self._run(self._delete_session_sync, session_id)
+ def _soft_delete_session_sync(self, session_id: str) -> bool:
+ with self._connect() as conn:
+ cur = conn.execute(
+ "UPDATE sessions SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL",
+ (time.time(), session_id),
+ )
+ conn.commit()
+ return cur.rowcount > 0
+
+ async def soft_delete_session(self, session_id: str) -> bool:
+ """Move a session to the recycle bin, where a restore can reach it."""
+ return await self._run(self._soft_delete_session_sync, session_id)
+
+ def _restore_session_sync(self, session_id: str) -> bool:
+ with self._connect() as conn:
+ cur = conn.execute(
+ "UPDATE sessions SET deleted_at = NULL WHERE id = ? AND deleted_at IS NOT NULL",
+ (session_id,),
+ )
+ conn.commit()
+ return cur.rowcount > 0
+
+ async def restore_session(self, session_id: str) -> bool:
+ return await self._run(self._restore_session_sync, session_id)
+
+ def _hard_delete_session_sync(self, session_id: str) -> bool:
+ with self._connect() as conn:
+ cur = conn.execute(
+ "DELETE FROM sessions WHERE id = ? AND deleted_at IS NOT NULL",
+ (session_id,),
+ )
+ conn.commit()
+ return cur.rowcount > 0
+
+ async def hard_delete_session(self, session_id: str) -> bool:
+ """Delete a session that is already in the recycle bin, permanently."""
+ return await self._run(self._hard_delete_session_sync, session_id)
+
+ def _list_deleted_sessions_sync(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> list[dict[str, Any]]:
+ return self._list_session_summaries_sync("WHERE s.deleted_at IS NOT NULL", limit, offset)
+
+ async def list_deleted_sessions(
+ self,
+ limit: int = 50,
+ offset: int = 0,
+ ) -> list[dict[str, Any]]:
+ return await self._run(self._list_deleted_sessions_sync, limit, offset)
+
def _add_message_sync(
self,
session_id: str,
@@ -2117,9 +2180,9 @@ class SQLiteSessionStore:
# their collection and ``sessionRoute`` sends a click back to the reader,
# so they belong in the list like everything else.
_WHERE_NATIVE = r"""
- WHERE s.id NOT LIKE 'imported\_%' ESCAPE '\'
+ WHERE s.id NOT LIKE 'imported\_%' ESCAPE '\' AND s.deleted_at IS NULL
"""
- _WHERE_IMPORTED = r"WHERE s.id LIKE 'imported\_%' ESCAPE '\'"
+ _WHERE_IMPORTED = r"WHERE s.id LIKE 'imported\_%' ESCAPE '\' AND s.deleted_at IS NULL"
def _list_session_summaries_sync(
self, where_sql: str, limit: int, offset: int
@@ -2587,6 +2650,14 @@ class SQLiteSessionStore:
conditions: list[str] = []
params: list[Any] = []
+ conditions.append(
+ """
+ NOT EXISTS (
+ SELECT 1 FROM sessions s
+ WHERE s.id = n.session_id AND s.deleted_at IS NOT NULL
+ )
+ """
+ )
if query.category_id is not None:
joins.append(" INNER JOIN notebook_entry_categories ec ON ec.entry_id = n.id")
conditions.append("ec.category_id = ?")
diff --git a/deeptutor_cli/session_cmd.py b/deeptutor_cli/session_cmd.py
index 06ee2df92..bfae8de71 100644
--- a/deeptutor_cli/session_cmd.py
+++ b/deeptutor_cli/session_cmd.py
@@ -39,7 +39,7 @@ def register(app: typer.Typer) -> None:
def delete_session(
session_id: str = typer.Argument(..., help="Session id."),
) -> None:
- """Delete a session and all of its turns/messages."""
+ """Move a session to the recycle bin (soft delete, recoverable)."""
maybe_run(_delete_session(session_id))
@app.command("rename")
diff --git a/tests/api/test_sessions_recycle.py b/tests/api/test_sessions_recycle.py
new file mode 100644
index 000000000..4642e1e98
--- /dev/null
+++ b/tests/api/test_sessions_recycle.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+
+class _RecycleBinStore:
+ """Minimal in-memory stand-in covering the recycle-bin lifecycle."""
+
+ def __init__(self) -> None:
+ self.sessions: dict[str, dict[str, Any]] = {}
+
+ def seed(self, session_id: str) -> None:
+ self.sessions[session_id] = {
+ "session_id": session_id,
+ "title": f"Session {session_id}",
+ "deleted_at": None,
+ }
+
+ async def delete_session(self, session_id: str) -> bool:
+ row = self.sessions.get(session_id)
+ if row is None or row.get("deleted_at") is not None:
+ return False
+ row["deleted_at"] = 1.0
+ return True
+
+ async def restore_session(self, session_id: str) -> bool:
+ row = self.sessions.get(session_id)
+ if row is None or row.get("deleted_at") is None:
+ return False
+ row["deleted_at"] = None
+ return True
+
+ async def purge_session(self, session_id: str) -> bool:
+ row = self.sessions.get(session_id)
+ if row is None or row.get("deleted_at") is None:
+ return False
+ del self.sessions[session_id]
+ return True
+
+ async def list_deleted_sessions(self, *, limit: int, offset: int):
+ deleted = [s for s in self.sessions.values() if s.get("deleted_at") is not None]
+ return deleted[offset : offset + limit]
+
+ async def get_session(self, session_id: str):
+ return self.sessions.get(session_id)
+
+
+def _make_store() -> _RecycleBinStore:
+ store = _RecycleBinStore()
+ store.seed("s-active")
+ store.seed("s-doomed")
+ return store
+
+
+async def test_delete_marks_recycled():
+ store = _make_store()
+ assert await store.delete_session("s-doomed")
+ assert store.sessions["s-doomed"]["deleted_at"] is not None
+ assert store.sessions["s-active"]["deleted_at"] is None
+
+
+async def test_restore_clears_deleted_at():
+ store = _make_store()
+ await store.delete_session("s-doomed")
+ assert await store.restore_session("s-doomed")
+ assert store.sessions["s-doomed"]["deleted_at"] is None
+
+
+async def test_restore_fails_when_not_deleted():
+ store = _make_store()
+ assert not await store.restore_session("s-active")
+
+
+async def test_purge_removes_only_deleted():
+ store = _make_store()
+ await store.delete_session("s-doomed")
+ assert await store.purge_session("s-doomed")
+ assert "s-doomed" not in store.sessions
+ assert not await store.purge_session("s-active")
+
+
+async def test_list_deleted_excludes_active():
+ store = _make_store()
+ await store.delete_session("s-doomed")
+ deleted = await store.list_deleted_sessions(limit=50, offset=0)
+ assert len(deleted) == 1
+ assert deleted[0]["session_id"] == "s-doomed"
+
+
+async def test_delete_fails_when_already_deleted():
+ store = _make_store()
+ await store.delete_session("s-doomed")
+ assert not await store.delete_session("s-doomed")
diff --git a/tests/multi_user/test_session_cleanup.py b/tests/multi_user/test_session_cleanup.py
index 3a7bc7c08..2d22099d7 100644
--- a/tests/multi_user/test_session_cleanup.py
+++ b/tests/multi_user/test_session_cleanup.py
@@ -16,7 +16,10 @@ def test_delete_session_cleans_only_current_user_artifacts(as_user, monkeypatch)
attachment_id = "upload-1"
class _SessionStore:
- async def delete_session(self, candidate: str) -> bool:
+ async def soft_delete_session(self, candidate: str) -> bool:
+ return candidate == session_id
+
+ async def hard_delete_session(self, candidate: str) -> bool:
return candidate == session_id
monkeypatch.setattr(sessions_router, "get_session_store", lambda: _SessionStore())
@@ -52,7 +55,11 @@ def test_delete_session_cleans_only_current_user_artifacts(as_user, monkeypatch)
with as_user("u_alice"):
response = await sessions_router.delete_session(session_id)
- assert response == {"deleted": True, "session_id": session_id}
+ assert response == {"deleted": True, "session_id": session_id, "recycled": True}
+ assert await _artifacts_exist("u_alice") == (True, True)
+ with as_user("u_alice"):
+ purge_response = await sessions_router.purge_session(session_id)
+ assert purge_response == {"purged": True, "session_id": session_id}
assert await _artifacts_exist("u_alice") == (False, False)
assert await _artifacts_exist("u_bob") == (True, True)
diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.py
index a2f7fe2fa..d7b78a3d3 100644
--- a/tests/services/session/test_sqlite_store.py
+++ b/tests/services/session/test_sqlite_store.py
@@ -666,12 +666,43 @@ def test_delete_notebook_entry(store: SQLiteSessionStore) -> None:
assert asyncio.run(store.delete_notebook_entry(99999)) is False
-def test_entries_cascade_on_session_delete(store: SQLiteSessionStore) -> None:
+def test_entries_follow_a_session_into_and_out_of_the_recycle_bin(
+ store: SQLiteSessionStore,
+) -> None:
+ session = asyncio.run(store.create_session())
+ asyncio.run(store.upsert_notebook_entries(session["id"], _make_items(("q1", "Q?", False))))
+ assert asyncio.run(store.list_notebook_entries())["total"] == 1
+
+ # A recycled session takes its entries out of view without destroying
+ # them, which is what makes the restore below whole.
+ asyncio.run(store.soft_delete_session(session["id"]))
+ assert asyncio.run(store.list_notebook_entries())["total"] == 0
+ assert asyncio.run(store.restore_session(session["id"]))
+ assert asyncio.run(store.list_notebook_entries())["total"] == 1
+
+ asyncio.run(store.soft_delete_session(session["id"]))
+ assert asyncio.run(store.hard_delete_session(session["id"]))
+ assert asyncio.run(store.list_notebook_entries())["total"] == 0
+
+
+def test_entries_cascade_when_a_session_is_deleted_outright(
+ store: SQLiteSessionStore,
+) -> None:
+ """`delete_session` skips the bin, so ON DELETE CASCADE fires at once.
+
+ This is the path the reading cleanups take: a workspace that is gone
+ takes its sessions with it, and those must not surface in the learner's
+ recycle bin to be restored into a workspace that no longer exists.
+ """
session = asyncio.run(store.create_session())
asyncio.run(store.upsert_notebook_entries(session["id"], _make_items(("q1", "Q?", False))))
assert asyncio.run(store.list_notebook_entries())["total"] == 1
- asyncio.run(store.delete_session(session["id"]))
+
+ assert asyncio.run(store.delete_session(session["id"]))
+
assert asyncio.run(store.list_notebook_entries())["total"] == 0
+ assert asyncio.run(store.list_deleted_sessions()) == []
+ assert asyncio.run(store.restore_session(session["id"])) is False
# ── Categories ────────────────────────────────────────────────────
diff --git a/web/components/sidebar/RecycleBinSection.tsx b/web/components/sidebar/RecycleBinSection.tsx
new file mode 100644
index 000000000..28620678e
--- /dev/null
+++ b/web/components/sidebar/RecycleBinSection.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Trash2, RotateCcw, ChevronDown, ChevronRight } from "lucide-react";
+import {
+ listRecycleBin,
+ restoreSession,
+ purgeSession,
+ type SessionSummary,
+} from "@/lib/session-api";
+
+export function RecycleBinSection() {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [sessions, setSessions] = useState<SessionSummary[]>([]);
+ const [loading, setLoading] = useState(false);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const result = await listRecycleBin();
+ setSessions(result);
+ } catch {
+ setSessions([]);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ if (open) void load();
+ }, [open, load]);
+
+ const handleRestore = useCallback(
+ async (sessionId: string) => {
+ await restoreSession(sessionId);
+ setSessions((prev) => prev.filter((s) => s.session_id !== sessionId));
+ },
+ [],
+ );
+
+ const handlePurge = useCallback(
+ async (sessionId: string) => {
+ if (!window.confirm(t("Permanently delete this session?"))) return;
+ await purgeSession(sessionId);
+ setSessions((prev) => prev.filter((s) => s.session_id !== sessionId));
+ },
+ [t],
+ );
+
+ return (
+ <div className="border-t border-[var(--border)] px-2 py-1">
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ className="flex w-full items-center gap-1.5 rounded-md px-2 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"
+ >
+ {open ? (
+ <ChevronDown className="h-3.5 w-3.5 shrink-0" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5 shrink-0" />
+ )}
+ <Trash2 className="h-3.5 w-3.5 shrink-0" />
+ <span className="truncate">{t("Recycle Bin")}</span>
+ {sessions.length > 0 && (
+ <span className="ml-auto shrink-0 rounded-full bg-[var(--muted)] px-1.5 text-[10px] leading-[18px] text-[var(--muted-foreground)]">
+ {sessions.length}
+ </span>
+ )}
+ </button>
+ {open && (
+ <div className="mt-1 max-h-[240px] overflow-y-auto">
+ {loading ? (
+ <p className="px-3 py-2 text-[11px] text-[var(--muted-foreground)]">{t("Loading...")}</p>
+ ) : sessions.length === 0 ? (
+ <p className="px-3 py-2 text-[11px] text-[var(--muted-foreground)]">{t("No deleted chats")}</p>
+ ) : (
+ sessions.map((session) => (
+ <div
+ key={session.session_id}
+ className="group flex items-center gap-1 rounded-md px-2 py-1.5 text-[12px] hover:bg-[var(--muted)]/40"
+ >
+ <span className="min-w-0 flex-1 truncate text-[var(--foreground)]">
+ {session.title || session.session_id}
+ </span>
+ <button
+ type="button"
+ onClick={() => void handleRestore(session.session_id)}
+ title={t("Restore")}
+ className="shrink-0 rounded p-1 text-[var(--muted-foreground)] opacity-0 hover:bg-[var(--muted)] hover:text-[var(--foreground)] group-hover:opacity-100"
+ >
+ <RotateCcw className="h-3.5 w-3.5" />
+ </button>
+ <button
+ type="button"
+ onClick={() => void handlePurge(session.session_id)}
+ title={t("Delete permanently")}
+ className="shrink-0 rounded p-1 text-[var(--destructive)] opacity-0 hover:bg-[var(--destructive)]/10 group-hover:opacity-100"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ ))
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/components/sidebar/SidebarShell.tsx b/web/components/sidebar/SidebarShell.tsx
index bbaf1dc7b..dc2adbec9 100644
--- a/web/components/sidebar/SidebarShell.tsx
+++ b/web/components/sidebar/SidebarShell.tsx
@@ -116,6 +116,8 @@ interface SidebarShellProps {
sessionId: string,
patch: SessionOrganizationPatch,
) => void | Promise<void>;
+ /** Optional recycle-bin section rendered below the session list. */
+ recycleBinSlot?: ReactNode;
/**
* Footer content rendered below the nav. Pass a render function to receive
* the current ``collapsed`` state so footer items (e.g. Admin / Sign out) can
@@ -137,6 +139,7 @@ export function SidebarShell({
masteryTopics = [],
readingCollections = [],
onOrganizeSession,
+ recycleBinSlot,
footerSlot,
}: SidebarShellProps) {
const pathname = usePathname();
@@ -391,6 +394,8 @@ export function SidebarShell({
</section>
) : null}
+ {recycleBinSlot}
+
{/* With no session list at all, fill the gap above the footer. */}
{(!showSessions ||
!onSelectSession ||
diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsx
index 504d2f1e5..cf84e2fb0 100644
--- a/web/components/sidebar/WorkspaceSidebar.tsx
+++ b/web/components/sidebar/WorkspaceSidebar.tsx
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslation } from "react-i18next";
import { SidebarShell } from "@/components/sidebar/SidebarShell";
+import { RecycleBinSection } from "@/components/sidebar/RecycleBinSection";
import { reconcileUnread } from "@/lib/session-unread";
import { LogoutButton } from "@/components/auth/LogoutButton";
import { AdminLink } from "@/components/auth/AdminLink";
@@ -224,6 +225,7 @@ export default function WorkspaceSidebar() {
onRenameSession={handleRenameSession}
onDeleteSession={handleDeleteSession}
onOrganizeSession={handleOrganizeSession}
+ recycleBinSlot={<RecycleBinSection />}
footerSlot={(collapsed) => (
<>
<ProfileLink collapsed={collapsed} />
diff --git a/web/lib/session-api.ts b/web/lib/session-api.ts
index dc3a1a2c5..f239d79d4 100644
--- a/web/lib/session-api.ts
+++ b/web/lib/session-api.ts
@@ -331,6 +331,35 @@ export async function deleteSession(sessionId: string): Promise<void> {
invalidateClientCache("sessions:");
}
+export async function listRecycleBin(
+ limit = 50,
+ offset = 0,
+): Promise<SessionSummary[]> {
+ const response = await apiFetch(
+ apiUrl(`/api/sessions/recycle-bin?limit=${limit}&offset=${offset}`),
+ );
+ const data = await expectJson<{ sessions: SessionSummary[] }>(response);
+ return data.sessions ?? [];
+}
+
+export async function restoreSession(sessionId: string): Promise<void> {
+ const response = await apiFetch(
+ apiUrl(`/api/sessions/${sessionId}/restore`),
+ { method: "POST" },
+ );
+ await expectJson<{ restored: boolean }>(response);
+ invalidateClientCache("sessions:");
+}
+
+export async function purgeSession(sessionId: string): Promise<void> {
+ const response = await apiFetch(
+ apiUrl(`/api/sessions/${sessionId}/purge`),
+ { method: "DELETE" },
+ );
+ await expectJson<{ purged: boolean }>(response);
+ invalidateClientCache("sessions:");
+}
+
export async function recordQuizResults(
sessionId: string,
answers: QuizResultItem[],
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 4895c76da..07e7fe55a 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -847,6 +847,11 @@
"llm-only": "llm-only",
"Copy": "Copy",
"Regenerate": "Regenerate",
+ "Recycle Bin": "Recycle Bin",
+ "Restore": "Restore",
+ "Delete permanently": "Delete permanently",
+ "No deleted chats": "No deleted chats",
+ "Permanently delete this session?": "Permanently delete this session?",
"Up to date": "Up to date",
"Update available": "Update available",
"Run Tour": "Run Tour",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 332f1f31e..e241f4f76 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -876,6 +876,11 @@
"llm-only": "仅 LLM",
"Copy": "复制",
"Regenerate": "重新生成",
+ "Recycle Bin": "回收站",
+ "Restore": "恢复",
+ "Delete permanently": "彻底删除",
+ "No deleted chats": "没有已删除的对话",
+ "Permanently delete this session?": "确定要彻底删除此对话吗?",
"Up to date": "已最新",
"Update available": "有新版本",
"Run Tour": "运行引导",