Files
DeepTutor/deeptutor_cli/notebook.py
Marcello Pichini 129aadcf57 fix(cli): print notebook text without parsing Rich markup (#2849)
Notebook names, descriptions, record titles and IDs were interpolated
into Rich markup strings, so `notebook show` and `notebook list` altered
bracketed text and crashed with MarkupError on an unmatched closing tag.
Render those values as rich.text.Text instead.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:26:02 +08:00

142 lines
5.4 KiB
Python

"""CLI commands for notebook record management."""
from __future__ import annotations
import json
from pathlib import Path
from rich.text import Text
import typer
from deeptutor.app import DeepTutorApp
from deeptutor.services.notebook.service import NotebookCorruptedError
from deeptutor.utils.file_types import FileTypeRouter
from .common import console, print_notebook_table
def register(app: typer.Typer) -> None:
@app.command("list")
def list_notebooks() -> None:
"""List notebooks."""
client = DeepTutorApp()
print_notebook_table(client.list_notebooks())
@app.command("create")
def create_notebook(
name: str = typer.Argument(..., help="Notebook name."),
description: str = typer.Option("", "--description", help="Notebook description."),
) -> None:
"""Create a notebook."""
client = DeepTutorApp()
notebook = client.create_notebook(name=name, description=description)
console.print_json(json.dumps(notebook, ensure_ascii=False, default=str))
@app.command("show")
def show_notebook(
notebook_id: str = typer.Argument(..., help="Notebook id."),
fmt: str = typer.Option("rich", "--format", help="Output format: rich | json."),
) -> None:
"""Show a notebook and its records."""
client = DeepTutorApp()
try:
notebook = client.get_notebook(notebook_id)
except NotebookCorruptedError as exc:
# The file is still on disk; say so instead of dumping a traceback.
console.print(Text.assemble(("Notebook file is damaged:", "red"), f" {exc}"))
raise typer.Exit(code=1)
if notebook is None:
console.print(Text.assemble(("Notebook not found:", "red"), f" {notebook_id}"))
raise typer.Exit(code=1)
if fmt == "json":
console.print_json(json.dumps(notebook, ensure_ascii=False, default=str))
return
console.print(
Text.assemble((str(notebook.get("name", "")), "bold"), f" ({notebook.get('id', '')})")
)
console.print(Text(str(notebook.get("description", "") or "")))
for record in notebook.get("records", []):
console.print(
Text.assemble(
"\n",
(str(record.get("id", "")), "cyan"),
f" {record.get('type', '')} {record.get('title', '')}",
)
)
@app.command("remove-record")
def remove_record(
notebook_id: str = typer.Argument(..., help="Notebook id."),
record_id: str = typer.Argument(..., help="Record id."),
) -> None:
"""Delete a notebook record."""
client = DeepTutorApp()
try:
success = client.remove_record(notebook_id, record_id)
except NotebookCorruptedError as exc:
console.print(Text.assemble(("Notebook file is damaged:", "red"), f" {exc}"))
raise typer.Exit(code=1)
if not success:
console.print(Text.assemble(("Record not found:", "red"), f" {record_id}"))
raise typer.Exit(code=1)
console.print(Text(f"Removed record {record_id} from notebook {notebook_id}"))
@app.command("add-md")
def add_md(
notebook_id: str = typer.Argument(..., help="Notebook id."),
file_path: str = typer.Argument(..., help="Path to the markdown file."),
title: str = typer.Option("", "--title", help="Record title (defaults to filename)."),
record_type: str = typer.Option(
"chat",
"--type",
help="Record type: chat, question, research, solve.",
),
) -> None:
"""Add a markdown file as a record to a notebook."""
path = Path(file_path)
if not path.exists():
console.print(Text.assemble(("File not found:", "red"), f" {file_path}"))
raise typer.Exit(code=1)
content = FileTypeRouter.decode_bytes(path.read_bytes())
record_title = title or path.stem
client = DeepTutorApp()
result = client.add_record(
notebook_ids=[notebook_id],
record_type=record_type,
title=record_title,
user_query="",
output=content,
)
record = result.get("record", {})
console.print(
Text.assemble(
("Added record", "green"),
f" {record.get('id', '')} to notebook {notebook_id}: {record_title}",
)
)
@app.command("replace-md")
def replace_md(
notebook_id: str = typer.Argument(..., help="Notebook id."),
record_id: str = typer.Argument(..., help="Record id."),
file_path: str = typer.Argument(..., help="Path to the markdown file."),
) -> None:
"""Replace a notebook record's output with content from a markdown file."""
path = Path(file_path)
if not path.exists():
console.print(Text.assemble(("File not found:", "red"), f" {file_path}"))
raise typer.Exit(code=1)
content = FileTypeRouter.decode_bytes(path.read_bytes())
client = DeepTutorApp()
updated = client.update_record(notebook_id, record_id, output=content)
if updated is None:
console.print(Text.assemble(("Record not found:", "red"), f" {record_id}"))
raise typer.Exit(code=1)
console.print(
Text.assemble(("Updated record", "green"), f" {record_id} in notebook {notebook_id}")
)