DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(chat): add inline markdown notes (#661)
XZHf187e2c48968
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsxindex 24aa5108c..3ceee2a30 100644--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx@@ -27,6 +27,7 @@ import {Lightbulb,MessageSquare,Microscope,+ NotebookPen,PenLine,Sparkles,type LucideIcon,@@ -2292,6 +2293,14 @@ export default function ChatPage() {label={t("Download Markdown")}title={t("Download chat history as Markdown")}/>+ <HeaderActionButton+ onClick={() =>+ viewerPanelRef.current?.openMarkdownNoteTab()+ }+ icon={NotebookPen}+ label={t("Markdown note")}+ title={t("Write Markdown in chat")}+ /><HeaderActionButtononClick={toggleViewerPanel}active={viewerPanelOpen}diff --git a/web/components/chat/home/ChatMarkdownNoteTab.tsx b/web/components/chat/home/ChatMarkdownNoteTab.tsxnew file mode 100644index 000000000..4a8fa551a--- /dev/null+++ b/web/components/chat/home/ChatMarkdownNoteTab.tsx@@ -0,0 +1,168 @@+"use client";++import {+ useCallback,+ useEffect,+ useState,+ type KeyboardEvent,+} from "react";+import {+ AlertCircle,+ ExternalLink,+ Loader2,+ NotebookPen,+ Save,+} from "lucide-react";+import { useTranslation } from "react-i18next";+import {+ createCoWriterDocument,+ updateCoWriterDocument,+} from "@/lib/co-writer-api";+import { notifyCoWriterChanged } from "@/lib/co-writer-events";+import {+ loadChatMarkdownNoteDraft,+ reconcileChatMarkdownNoteAfterSave,+ isChatMarkdownNoteDirty,+ persistChatMarkdownNote,+ saveChatMarkdownNoteDraft,+} from "@/lib/chat-markdown-note";++const noteStore = {+ create: createCoWriterDocument,+ update: updateCoWriterDocument,+};++export default function ChatMarkdownNoteTab({+ sessionId,+}: {+ sessionId: string | null;+}) {+ const { t } = useTranslation();+ const [draft, setDraft] = useState(() =>+ loadChatMarkdownNoteDraft(sessionId),+ );+ const { title, content, saved } = draft;+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const dirty = isChatMarkdownNoteDirty({ title, content }, saved);+ const canSave = dirty && !saving;++ useEffect(() => {+ saveChatMarkdownNoteDraft(sessionId, draft);+ }, [draft, sessionId]);++ const save = useCallback(async () => {+ if (!canSave) return;+ setSaving(true);+ setError(null);+ try {+ const nextSaved = await persistChatMarkdownNote(+ { title, content },+ saved,+ noteStore,+ );+ setDraft((latest) => ({+ ...reconcileChatMarkdownNoteAfterSave(+ { title: latest.title, content: latest.content },+ { title, content },+ nextSaved,+ ),+ saved: nextSaved,+ }));+ notifyCoWriterChanged();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ }, [canSave, content, saved, title]);++ const handleKeyDown = useCallback(+ (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (+ event.key.toLowerCase() === "s" &&+ (event.metaKey || event.ctrlKey)+ ) {+ event.preventDefault();+ void save();+ }+ },+ [save],+ );++ return (+ <form+ className="flex h-full min-h-0 flex-col"+ onSubmit={(event) => {+ event.preventDefault();+ void save();+ }}+ >+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-[var(--border)]/40 bg-[var(--card)] px-3 py-2">+ <NotebookPen+ size={15}+ strokeWidth={1.8}+ className="shrink-0 text-[var(--muted-foreground)]"+ />+ <input+ type="text"+ value={title}+ onChange={(event) => {+ setDraft((latest) => ({ ...latest, title: event.target.value }));+ setError(null);+ }}+ placeholder={t("Untitled Co-Writer Document")}+ aria-label={t("Note title")}+ maxLength={200}+ className="min-w-[140px] flex-1 basis-40 rounded-md border border-transparent bg-transparent px-1 py-1 text-[13px] font-medium text-[var(--foreground)] outline-none transition-colors placeholder:text-[var(--muted-foreground)]/60 hover:border-[var(--border)]/50 focus:border-[var(--primary)]/40 focus:bg-[var(--background)]"+ />+ {saved && !dirty ? (+ <span className="shrink-0 text-[11px] font-medium text-[var(--muted-foreground)]">+ {t("Saved")}+ </span>+ ) : null}+ {saved ? (+ <a+ href={`/co-writer/${encodeURIComponent(saved.id)}`}+ className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-[var(--border)]/55 px-2 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--primary)]/35 hover:text-[var(--primary)]"+ >+ <ExternalLink size={11} strokeWidth={1.9} />+ {t("Open in Co-Writer")}+ </a>+ ) : null}+ <button+ type="submit"+ disabled={!canSave}+ className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md bg-[var(--primary)] px-2.5 text-[11px] font-semibold text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"+ >+ {saving ? (+ <Loader2 size={11} className="animate-spin" />+ ) : (+ <Save size={11} strokeWidth={1.9} />+ )}+ {t("Save")}+ </button>+ </div>+ {error ? (+ <div+ role="alert"+ className="flex shrink-0 items-start gap-2 border-b border-[var(--border)]/30 bg-[var(--destructive)]/8 px-3 py-2 text-[11px] leading-snug text-[var(--destructive)]"+ >+ <AlertCircle size={12} strokeWidth={1.9} className="mt-[1px] shrink-0" />+ <span>{t("Save failed")}{error ? `: ${error}` : ""}</span>+ </div>+ ) : null}+ <textarea+ value={content}+ onChange={(event) => {+ setDraft((latest) => ({ ...latest, content: event.target.value }));+ setError(null);+ }}+ onKeyDown={handleKeyDown}+ placeholder={t("Start writing in Markdown...")}+ aria-label={t("Markdown")}+ className="min-h-0 flex-1 resize-none bg-[var(--card)] px-3 py-3 font-mono text-[12.5px] leading-relaxed text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/60"+ />+ </form>+ );+}diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsxindex b7c92e301..21a47c38d 100644--- a/web/components/chat/home/SessionViewerPanel.tsx+++ b/web/components/chat/home/SessionViewerPanel.tsx@@ -37,6 +37,7 @@ import {GraduationCap,Loader2,MessageSquarePlus,+ NotebookPen,Paperclip,X,} from "lucide-react";@@ -90,6 +91,10 @@ const OfficeTextPreview = dynamic(const FallbackPreview = dynamic(() => import("@/components/chat/preview/previewers/FallbackPreview"),);+const ChatMarkdownNoteTabBody = dynamic(+ () => import("@/components/chat/home/ChatMarkdownNoteTab"),+ { ssr: false },+);const Geogebra = dynamic(() => import("@/components/Geogebra"), {ssr: false,});@@ -135,6 +140,7 @@ function readStoredViewerWidth(): number {type ViewerTab =| { kind: "file"; id: string; label: string; source: FilePreviewSource }| { kind: "web"; id: string; label: string; url: string }+ | { kind: "markdown-note"; id: string; label: string }| {kind: "quiz-followup";id: string;@@ -164,6 +170,8 @@ type ViewerTab =export interface SessionViewerPanelHandle {openFileTab(a: MessageAttachment): void;openWebTab(url: string): void;+ /** Opens the session-scoped inline Markdown editor tab. */+ openMarkdownNoteTab(): void;/** Opens (or focuses) the follow-up chat tab for a quiz question. */openQuizFollowupTab(context: QuizFollowupTabContext): void;/** Opens an independent Little Tutor thread grounded in selected chat text. */@@ -199,6 +207,8 @@ function webTabIdFor(url: string): string {return `web:${url}`;}+const markdownNoteTabId = "markdown-note";+function quizFollowupTabIdFor(questionKey: string): string {return `quiz-followup:${questionKey}`;}@@ -362,6 +372,26 @@ function SessionViewerPanelInner([onAutoOpen],);+ const openMarkdownNoteTab = useCallback(() => {+ setTabs((prev) => {+ const existingIdx = prev.findIndex(+ (tab) => tab.id === markdownNoteTabId,+ );+ if (existingIdx >= 0) {+ setActiveTabId(markdownNoteTabId);+ return prev;+ }+ const next: ViewerTab = {+ kind: "markdown-note",+ id: markdownNoteTabId,+ label: t("Markdown note"),+ };+ setActiveTabId(markdownNoteTabId);+ return [...prev, next];+ });+ onAutoOpen();+ }, [onAutoOpen, t]);+const openQuizFollowupTab = useCallback((context: QuizFollowupTabContext) => {setTabs((prev) => {@@ -527,6 +557,7 @@ function SessionViewerPanelInner(() => ({openFileTab,openWebTab,+ openMarkdownNoteTab,openQuizFollowupTab,openSelectionTutorTab,openGeogebraTab,@@ -536,6 +567,7 @@ function SessionViewerPanelInner([openFileTab,openWebTab,+ openMarkdownNoteTab,openQuizFollowupTab,openSelectionTutorTab,openGeogebraTab,@@ -648,6 +680,11 @@ function SessionViewerPanelInner(<FileTabBody source={activeTab.source} />) : activeTab?.kind === "web" ? (<WebTabBody key={activeTab.url} url={activeTab.url} />+ ) : activeTab?.kind === "markdown-note" ? (+ <ChatMarkdownNoteTabBody+ key={`${activeTab.id}:${sessionId ?? "pending"}`}+ sessionId={sessionId}+ />) : activeTab?.kind === "quiz-followup" ? (<QuizFollowupTabBodykey={activeTab.context.questionKey}@@ -737,7 +774,9 @@ function TabBar({const Icon =tab.kind === "web"? Globe- : tab.kind === "selection-tutor"+ : tab.kind === "markdown-note"+ ? NotebookPen+ : tab.kind === "selection-tutor"? GraduationCap: tab.kind === "quiz-followup"? MessageSquarePlusdiff --git a/web/lib/chat-markdown-note.ts b/web/lib/chat-markdown-note.tsnew file mode 100644index 000000000..87564db71--- /dev/null+++ b/web/lib/chat-markdown-note.ts@@ -0,0 +1,164 @@+import type { CoWriterDocument } from "@/lib/co-writer-api";++export interface ChatMarkdownNoteInput {+ title: string;+ content: string;+}++export interface SavedChatMarkdownNote {+ id: string;+ title: string;+ content: string;+}++export interface ChatMarkdownNoteDraft {+ title: string;+ content: string;+ saved: SavedChatMarkdownNote | null;+}++export const EMPTY_CHAT_MARKDOWN_NOTE_DRAFT: ChatMarkdownNoteDraft = {+ title: "",+ content: "",+ saved: null,+};++const CHAT_MARKDOWN_NOTE_KEY_PREFIX = "dt:chat-markdown-note:";+const PENDING_CHAT_MARKDOWN_NOTE_KEY = `${CHAT_MARKDOWN_NOTE_KEY_PREFIX}pending`;++type ChatMarkdownNoteStorage = Pick<+ Storage,+ "getItem" | "setItem" | "removeItem"+>;++function storageKey(sessionId: string | null): string {+ return sessionId+ ? `${CHAT_MARKDOWN_NOTE_KEY_PREFIX}${sessionId}`+ : PENDING_CHAT_MARKDOWN_NOTE_KEY;+}++function parseDraft(raw: string | null): ChatMarkdownNoteDraft | null {+ if (!raw) return null;+ try {+ const value = JSON.parse(raw) as Partial<ChatMarkdownNoteDraft>;+ if (+ typeof value.title !== "string" ||+ typeof value.content !== "string" ||+ (value.saved !== null &&+ (typeof value.saved !== "object" ||+ typeof value.saved?.id !== "string" ||+ typeof value.saved.title !== "string" ||+ typeof value.saved.content !== "string"))+ ) {+ return null;+ }+ return {+ title: value.title,+ content: value.content,+ saved: value.saved+ ? {+ id: value.saved.id,+ title: value.saved.title,+ content: value.saved.content,+ }+ : null,+ };+ } catch {+ return null;+ }+}++export function loadChatMarkdownNoteDraft(+ sessionId: string | null,+ storage: ChatMarkdownNoteStorage | null = typeof window === "undefined"+ ? null+ : window.localStorage,+): ChatMarkdownNoteDraft {+ if (!storage) return EMPTY_CHAT_MARKDOWN_NOTE_DRAFT;++ const key = storageKey(sessionId);+ const draft = parseDraft(storage.getItem(key));+ if (!sessionId) return draft ?? EMPTY_CHAT_MARKDOWN_NOTE_DRAFT;++ // A note started before a new chat receives its session id is adopted by+ // that session instead of leaking into the next new chat.+ const pending = parseDraft(+ storage.getItem(PENDING_CHAT_MARKDOWN_NOTE_KEY),+ );+ if (!draft && pending) {+ try {+ storage.setItem(key, JSON.stringify(pending));+ storage.removeItem(PENDING_CHAT_MARKDOWN_NOTE_KEY);+ } catch {+ // If adoption cannot be persisted, return the pending draft so this+ // session still gets the content in memory.+ }+ return pending;+ }+ return draft ?? EMPTY_CHAT_MARKDOWN_NOTE_DRAFT;+}++export function saveChatMarkdownNoteDraft(+ sessionId: string | null,+ draft: ChatMarkdownNoteDraft,+ storage: ChatMarkdownNoteStorage | null = typeof window === "undefined"+ ? null+ : window.localStorage,+): void {+ if (!storage) return;+ try {+ storage.setItem(storageKey(sessionId), JSON.stringify(draft));+ } catch {+ // Storage can be unavailable or full. The in-memory draft remains usable.+ }+}++export interface ChatMarkdownNoteStore {+ create(payload: {+ title?: string | null;+ content?: string;+ }): Promise<CoWriterDocument>;+ update(+ docId: string,+ payload: { title?: string | null; content?: string | null },+ ): Promise<CoWriterDocument>;+}++export function isChatMarkdownNoteDirty(+ input: ChatMarkdownNoteInput,+ saved: SavedChatMarkdownNote | null,+): boolean {+ const title = input.title.trim();+ if (!saved) return Boolean(title || input.content.trim());+ return title !== saved.title.trim() || input.content !== saved.content;+}++export async function persistChatMarkdownNote(+ input: ChatMarkdownNoteInput,+ saved: SavedChatMarkdownNote | null,+ store: ChatMarkdownNoteStore,+): Promise<SavedChatMarkdownNote> {+ const title = input.title.trim();+ const payload = { title: title || null, content: input.content };+ const document = saved+ ? await store.update(saved.id, payload)+ : await store.create(payload);++ return {+ id: document.id,+ title: document.title,+ content: document.content ?? "",+ };+}++export function reconcileChatMarkdownNoteAfterSave(+ latest: ChatMarkdownNoteInput,+ request: ChatMarkdownNoteInput,+ saved: SavedChatMarkdownNote,+): ChatMarkdownNoteInput {+ return {+ title: latest.title === request.title ? saved.title : latest.title,+ content:+ latest.content === request.content ? saved.content : latest.content,+ };+}diff --git a/web/lib/co-writer-api.ts b/web/lib/co-writer-api.tsindex 182ba1dd3..840b1a0bc 100644--- a/web/lib/co-writer-api.ts+++ b/web/lib/co-writer-api.ts@@ -39,7 +39,7 @@ export async function listCoWriterDocuments(): Promise<}export async function createCoWriterDocument(payload?: {- title?: string;+ title?: string | null;content?: string;}): Promise<CoWriterDocument> {const res = await apiFetch(apiUrl(`${BASE}/documents`), {diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 846e8a812..06bbb9da7 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -351,6 +351,10 @@"Save to Notebook": "Save to Notebook","Download Markdown": "Download Markdown","Download chat history as Markdown": "Download chat history as Markdown",+ "Markdown note": "Markdown note",+ "Write Markdown in chat": "Write Markdown in chat",+ "Note title": "Note title",+ "Open in Co-Writer": "Open in Co-Writer","Saved to notebook.": "Saved to notebook.","Add some content before saving to a notebook.": "Add some content before saving to a notebook.","Untitled Co-Writer Document": "Untitled Co-Writer Document",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1279f3d24..c6c347788 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -351,6 +351,10 @@"Save to Notebook": "保存到笔记本","Download Markdown": "下载 Markdown","Download chat history as Markdown": "将聊天记录下载为 Markdown 文件",+ "Markdown note": "Markdown 笔记",+ "Write Markdown in chat": "在聊天中写 Markdown",+ "Note title": "笔记标题",+ "Open in Co-Writer": "打开智能写作","Saved to notebook.": "已保存到笔记本。","Add some content before saving to a notebook.": "请先写一些内容再保存到笔记本。","Untitled Co-Writer Document": "未命名的 Co-Writer 文档",diff --git a/web/tests/chat-markdown-note.test.ts b/web/tests/chat-markdown-note.test.tsnew file mode 100644index 000000000..e1c55f706--- /dev/null+++ b/web/tests/chat-markdown-note.test.ts@@ -0,0 +1,216 @@+import test from "node:test";+import assert from "node:assert/strict";+import {+ loadChatMarkdownNoteDraft,+ isChatMarkdownNoteDirty,+ persistChatMarkdownNote,+ reconcileChatMarkdownNoteAfterSave,+ saveChatMarkdownNoteDraft,+ type ChatMarkdownNoteStore,+ type SavedChatMarkdownNote,+} from "../lib/chat-markdown-note";+import type { CoWriterDocument } from "../lib/co-writer-api";++function document(fields: Partial<CoWriterDocument> = {}): CoWriterDocument {+ return {+ id: "doc-1",+ title: "Note",+ content: "# Note",+ created_at: 1,+ updated_at: 2,+ ...fields,+ };+}++test("a blank unsaved markdown note is not saveable", () => {+ assert.equal(+ isChatMarkdownNoteDirty({ title: " ", content: " " }, null),+ false,+ );+});++test("an unsaved markdown note with a title or content is dirty", () => {+ assert.equal(+ isChatMarkdownNoteDirty({ title: "Idea", content: "" }, null),+ true,+ );+ assert.equal(+ isChatMarkdownNoteDirty({ title: "", content: "# Idea" }, null),+ true,+ );+});++test("saved markdown notes compare trimmed titles and exact content", () => {+ const saved: SavedChatMarkdownNote = {+ id: "doc-1",+ title: "Note",+ content: "# Note",+ };++ assert.equal(+ isChatMarkdownNoteDirty({ title: " Note ", content: "# Note" }, saved),+ false,+ );+ assert.equal(+ isChatMarkdownNoteDirty({ title: "New", content: "# Note" }, saved),+ true,+ );+ assert.equal(+ isChatMarkdownNoteDirty({ title: "Note", content: "# New" }, saved),+ true,+ );+});++test("the first markdown-note save creates a Co-Writer document", async () => {+ const created: string[] = [];+ const updated: string[] = [];+ const store: ChatMarkdownNoteStore = {+ async create(payload) {+ created.push(JSON.stringify(payload));+ return document({ id: "new-doc", title: "Derived", content: "# Idea" });+ },+ async update(docId) {+ updated.push(docId);+ return document();+ },+ };++ const saved = await persistChatMarkdownNote(+ { title: " ", content: "# Idea" },+ null,+ store,+ );++ assert.deepEqual(created, ['{"title":null,"content":"# Idea"}']);+ assert.deepEqual(updated, []);+ assert.deepEqual(saved, {+ id: "new-doc",+ title: "Derived",+ content: "# Idea",+ });+});++test("later markdown-note saves update the existing Co-Writer document", async () => {+ const created: string[] = [];+ const updated: Array<{ docId: string; payload: string }> = [];+ const store: ChatMarkdownNoteStore = {+ async create() {+ created.push("create");+ return document();+ },+ async update(docId, payload) {+ updated.push({ docId, payload: JSON.stringify(payload) });+ return document({+ id: docId,+ title: payload.title ?? "",+ content: payload.content ?? "",+ });+ },+ };+ const saved: SavedChatMarkdownNote = {+ id: "doc-1",+ title: "Note",+ content: "# Note",+ };++ const next = await persistChatMarkdownNote(+ { title: " New note ", content: "# Updated" },+ saved,+ store,+ );++ assert.deepEqual(created, []);+ assert.deepEqual(updated, [+ { docId: "doc-1", payload: '{"title":"New note","content":"# Updated"}' },+ ]);+ assert.deepEqual(next, {+ id: "doc-1",+ title: "New note",+ content: "# Updated",+ });+});++test("a save response does not overwrite edits made while it was in flight", () => {+ const reconciled = reconcileChatMarkdownNoteAfterSave(+ { title: "New title", content: "# Newer content" },+ { title: "Old title", content: "# Older content" },+ { id: "doc-1", title: "Server title", content: "# Older content" },+ );++ assert.deepEqual(reconciled, {+ title: "New title",+ content: "# Newer content",+ });+});++test("markdown-note drafts persist and restore by chat session", () => {+ const storage = new Map<string, string>();+ const noteStorage = createStorage(storage);++ saveChatMarkdownNoteDraft(+ "session-1",+ {+ title: "Session note",+ content: "# Session content",+ saved: { id: "doc-1", title: "Session note", content: "# Session" },+ },+ noteStorage,+ );++ assert.deepEqual(loadChatMarkdownNoteDraft("session-1", noteStorage), {+ title: "Session note",+ content: "# Session content",+ saved: { id: "doc-1", title: "Session note", content: "# Session" },+ });+ assert.deepEqual(loadChatMarkdownNoteDraft("session-2", noteStorage), {+ title: "",+ content: "",+ saved: null,+ });+});++test("a pending markdown-note draft is adopted by its chat session", () => {+ const storage = new Map<string, string>();+ const noteStorage = createStorage(storage);++ saveChatMarkdownNoteDraft(+ null,+ {+ title: "Pending note",+ content: "# Pending",+ saved: null,+ },+ noteStorage,+ );++ assert.deepEqual(loadChatMarkdownNoteDraft("session-1", noteStorage), {+ title: "Pending note",+ content: "# Pending",+ saved: null,+ });+ assert.equal(storage.has("dt:chat-markdown-note:pending"), false);+ assert.equal(+ storage.get("dt:chat-markdown-note:session-1"),+ JSON.stringify({+ title: "Pending note",+ content: "# Pending",+ saved: null,+ }),+ );+});++function createStorage(+ values: Map<string, string>,+): Parameters<typeof saveChatMarkdownNoteDraft>[2] {+ return {+ getItem(key) {+ return values.get(key) ?? null;+ },+ setItem(key, value) {+ values.set(key, value);+ },+ removeItem(key) {+ values.delete(key);+ },+ };+}