Files
DeepTutor/deeptutor_cli/session_cmd.py
evan188199-tech 9b066b5f98 feat(sessions): add recycle bin for deleted chats (#1398)
* feat(sessions): add recycle bin for deleted chats

Implements soft-delete for chat sessions so users can restore
accidentally deleted conversations from a recycle bin.

Backend:
- Schema migration adds deleted_at REAL column to sessions
- delete_session becomes a soft-delete (sets deleted_at timestamp)
- New store methods: restore_session, purge_session, list_deleted_sessions
- Session list queries exclude soft-deleted sessions
- API endpoints: GET /sessions/recycle-bin, POST /{id}/restore,
  DELETE /{id}/purge (purge triggers attachment/mastery cleanup)

Frontend:
- RecycleBinSection: collapsible sidebar section listing deleted
  sessions with Restore and Delete permanently actions
- Wired into SidebarShell via recycleBinSlot prop
- API client functions for list, restore, and purge
- en/zh translations for all recycle-bin UI strings

Tests: 6 backend tests covering the soft-delete lifecycle

* style: apply ruff format to sqlite_store

* fix(sessions): preserve recycled chat artifacts

* feat(sessions): fold #1444's backend into this recycle bin

#1444 built the same feature from the other end. This PR had the SQLite
column, the routes and the sidebar UI; #1444 had the protocol declarations,
the PocketBase implementation and the CLI wording. Neither shipped alone —
this one left multi-user deployments answering AttributeError on
/recycle-bin, and #1444 built a bin nobody could see. Closes #1444; its
backend is here.

Kept from here: one `deleted_at` column. #1444 carried `is_deleted` beside it
in both backends, and `deleted_at IS NOT NULL` already says everything the
boolean did — PocketBase now derives the outward `is_deleted` field from the
timestamp instead of storing it twice.

Taken from #1444: the naming, which turns out to fix the residual both PRs
shipped with. `delete_session` keeps meaning what every existing caller
already meant by it — remove the row — so `reading.py`'s two internal
cleanups need no patch: a deleted reading workspace still takes its sessions
with it instead of depositing them in a learner's bin, where restoring one
would resurrect a session pointing at a workspace that no longer exists. The
chat surface's delete is a separate, explicitly named `soft_delete_session`,
and `hard_delete_session` empties the bin. Both backends agree, and the
protocol declares all five so a backend cannot silently lack one again.

`test_entries_cascade_on_session_purge` becomes two tests, because there are
now two deletions worth pinning: one the bin can undo, and one that skips it
and cascades immediately.

Co-Authored-By: sjagadee <srini.jagadeesh@gmail.com>
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
Co-authored-by: sjagadee <srini.jagadeesh@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 01:43:35 +08:00

102 lines
3.3 KiB
Python

"""CLI commands for shared session management."""
from __future__ import annotations
import json
import typer
from deeptutor.app import DeepTutorApp
from .chat import ChatState, _chat_repl
from .common import console, maybe_run, print_session_table
def register(app: typer.Typer) -> None:
@app.command("list")
def list_sessions(
limit: int = typer.Option(20, "--limit", help="Maximum sessions to show."),
) -> None:
"""List existing sessions."""
maybe_run(_list_sessions(limit))
@app.command("show")
def show_session(
session_id: str = typer.Argument(..., help="Session id."),
fmt: str = typer.Option("rich", "--format", help="Output format: rich | json."),
) -> None:
"""Show a session and its persisted messages."""
maybe_run(_show_session(session_id, fmt))
@app.command("open")
def open_session(
session_id: str = typer.Argument(..., help="Session id."),
) -> None:
"""Enter the interactive chat REPL with an existing session."""
maybe_run(_chat_repl(ChatState(session_id=session_id)))
@app.command("delete")
def delete_session(
session_id: str = typer.Argument(..., help="Session id."),
) -> None:
"""Move a session to the recycle bin (soft delete, recoverable)."""
maybe_run(_delete_session(session_id))
@app.command("rename")
def rename_session(
session_id: str = typer.Argument(..., help="Session id."),
title: str = typer.Option(..., "--title", help="New session title."),
) -> None:
"""Rename a session."""
maybe_run(_rename_session(session_id, title))
async def _list_sessions(limit: int) -> None:
client = DeepTutorApp()
sessions = await client.list_sessions(limit=limit)
print_session_table(sessions)
async def _show_session(session_id: str, fmt: str) -> None:
client = DeepTutorApp()
session = await client.get_session(session_id)
if session is None:
console.print(f"[red]Session not found:[/] {session_id}")
raise typer.Exit(code=1)
if fmt == "json":
console.print(json.dumps(session, ensure_ascii=False, indent=2, default=str))
return
console.print(f"[bold]{session.get('title', '')}[/] ({session.get('id', '')})")
console.print(
f"[dim]capability={session.get('capability', '') or 'chat'} "
f"status={session.get('status', '')} "
f"messages={len(session.get('messages', []))}[/]",
highlight=False,
)
for message in session.get("messages", []):
role = str(message.get("role", "")).upper()
content = str(message.get("content", "") or "").strip()
console.print(f"\n[cyan]{role}[/]")
if content:
console.print(content)
async def _delete_session(session_id: str) -> None:
client = DeepTutorApp()
success = await client.delete_session(session_id)
if not success:
console.print(f"[red]Session not found:[/] {session_id}")
raise typer.Exit(code=1)
console.print(f"Deleted session {session_id}")
async def _rename_session(session_id: str, title: str) -> None:
client = DeepTutorApp()
success = await client.rename_session(session_id, title)
if not success:
console.print(f"[red]Session not found:[/] {session_id}")
raise typer.Exit(code=1)
console.print(f"Renamed {session_id} -> {title}")