Skip to content

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

Merge pull request #1062 from evan188199-tech

Bingxi Zhao (Frank)2774d8b0166c
diff --cc web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 2c3cd00d5,3ceee2a30..604ce548e
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@@ -11,7 -11,27 +11,12 @@@ import
} from "react";
import { useParams, useRouter } from "next/navigation";
- import { GraduationCap, PenLine, type LucideIcon } from "lucide-react";
+ import {
- BarChart3,
- BookOpenText,
- BrainCircuit,
- CircleHelp,
- Clapperboard,
- Code2,
- Compass,
- Database,
- FileSearch,
- Globe,
+ GraduationCap,
- Image as ImageIcon,
- Lightbulb,
- MessageSquare,
- Microscope,
+ NotebookPen,
+ PenLine,
- Sparkles,
+ type LucideIcon,
+ } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { SelectedRecord } from "@/lib/notebook-selection-types";
import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";
diff --cc web/components/chat/home/ChatMarkdownNoteTab.tsx
index 000000000,4a8fa551a..8c01cb123
mode 000000,100644..100644
--- a/web/components/chat/home/ChatMarkdownNoteTab.tsx
+++ b/web/components/chat/home/ChatMarkdownNoteTab.tsx
@@@ -1,0 -1,168 +1,187 @@@
+ "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 { useAuthStatus } from "@/hooks/useAuthStatus";
+ import {
+ createCoWriterDocument,
+ updateCoWriterDocument,
+ } from "@/lib/co-writer-api";
+ import { notifyCoWriterChanged } from "@/lib/co-writer-events";
+ import {
+ loadChatMarkdownNoteDraft,
++ EMPTY_CHAT_MARKDOWN_NOTE_DRAFT,
+ 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 auth = useAuthStatus();
++ const ownerId =
++ !auth.loading && auth.statusAvailable
++ ? auth.enabled
++ ? auth.userId
++ : "local"
++ : null;
++ const draftScope = ownerId ? `${ownerId}:${sessionId ?? "pending"}` : null;
++ const [loadedScope, setLoadedScope] = useState<string | null>(null);
++ const [draft, setDraft] = useState(() => ({
++ ...EMPTY_CHAT_MARKDOWN_NOTE_DRAFT,
++ }));
+ 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]);
++ if (!ownerId || !draftScope) return;
++ setDraft(loadChatMarkdownNoteDraft(ownerId, sessionId));
++ setLoadedScope(draftScope);
++ setError(null);
++ }, [draftScope, ownerId, sessionId]);
++
++ useEffect(() => {
++ if (!ownerId || loadedScope !== draftScope) return;
++ saveChatMarkdownNoteDraft(ownerId, sessionId, draft);
++ }, [draft, draftScope, loadedScope, ownerId, 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 --cc web/hooks/useAuthStatus.ts
index 113d6564a,113d6564a..3f99171b1
--- a/web/hooks/useAuthStatus.ts
+++ b/web/hooks/useAuthStatus.ts
@@@ -10,6 -10,6 +10,10 @@@ export interface AuthStatusState
authenticated: boolean;
/** Whether the authenticated user is an admin. */
isAdmin: boolean;
++ /** Stable account id for account-scoped browser state. */
++ userId: string | null;
++ /** False when the runtime status endpoint could not be reached. */
++ statusAvailable: boolean;
/** True until the first status fetch resolves. */
loading: boolean;
}
@@@ -18,6 -18,6 +22,8 @@@ const INITIAL: AuthStatusState =
enabled: false,
authenticated: false,
isAdmin: false,
++ userId: null,
++ statusAvailable: false,
loading: true,
};
@@@ -44,6 -44,6 +50,11 @@@ function loadAuthStatus(): Promise<Auth
enabled: Boolean(status?.enabled),
authenticated: Boolean(status?.authenticated),
isAdmin: status?.role === "admin",
++ userId:
++ typeof status?.user_id === "string" && status.user_id.trim()
++ ? status.user_id
++ : null,
++ statusAvailable: status !== null,
loading: false,
}))
.finally(() => {
diff --cc web/lib/chat-markdown-note.ts
index 000000000,87564db71..13f615f8d
mode 000000,100644..100644
--- a/web/lib/chat-markdown-note.ts
+++ b/web/lib/chat-markdown-note.ts
@@@ -1,0 -1,164 +1,165 @@@
+ 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 storageKey(ownerId: string, sessionId: string | null): string {
++ const owner = encodeURIComponent(ownerId);
++ const session = sessionId ? encodeURIComponent(sessionId) : "pending";
++ return `${CHAT_MARKDOWN_NOTE_KEY_PREFIX}${owner}:${session}`;
+ }
+
+ 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(
++ ownerId: string,
+ 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 key = storageKey(ownerId, 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),
++ storage.getItem(storageKey(ownerId, null)),
+ );
+ if (!draft && pending) {
+ try {
+ storage.setItem(key, JSON.stringify(pending));
- storage.removeItem(PENDING_CHAT_MARKDOWN_NOTE_KEY);
++ storage.removeItem(storageKey(ownerId, null));
+ } 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(
++ ownerId: string,
+ 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));
++ storage.setItem(storageKey(ownerId, 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 --cc web/tests/chat-markdown-note.test.ts
index 000000000,e1c55f706..961810ac1
mode 000000,100644..100644
--- a/web/tests/chat-markdown-note.test.ts
+++ b/web/tests/chat-markdown-note.test.ts
@@@ -1,0 -1,216 +1,239 @@@
+ 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(
++ "user-1",
+ "session-1",
+ {
+ title: "Session note",
+ content: "# Session content",
+ saved: { id: "doc-1", title: "Session note", content: "# Session" },
+ },
+ noteStorage,
+ );
+
- assert.deepEqual(loadChatMarkdownNoteDraft("session-1", noteStorage), {
++ assert.deepEqual(loadChatMarkdownNoteDraft("user-1", "session-1", noteStorage), {
+ title: "Session note",
+ content: "# Session content",
+ saved: { id: "doc-1", title: "Session note", content: "# Session" },
+ });
- assert.deepEqual(loadChatMarkdownNoteDraft("session-2", noteStorage), {
++ assert.deepEqual(loadChatMarkdownNoteDraft("user-1", "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(
++ "user-1",
+ null,
+ {
+ title: "Pending note",
+ content: "# Pending",
+ saved: null,
+ },
+ noteStorage,
+ );
+
- assert.deepEqual(loadChatMarkdownNoteDraft("session-1", noteStorage), {
++ assert.deepEqual(loadChatMarkdownNoteDraft("user-1", "session-1", noteStorage), {
+ title: "Pending note",
+ content: "# Pending",
+ saved: null,
+ });
- assert.equal(storage.has("dt:chat-markdown-note:pending"), false);
++ assert.equal(storage.has("dt:chat-markdown-note:user-1:pending"), false);
+ assert.equal(
- storage.get("dt:chat-markdown-note:session-1"),
++ storage.get("dt:chat-markdown-note:user-1:session-1"),
+ JSON.stringify({
+ title: "Pending note",
+ content: "# Pending",
+ saved: null,
+ }),
+ );
+ });
+
++test("markdown-note drafts are isolated when the signed-in account changes", () => {
++ const storage = new Map<string, string>();
++ const noteStorage = createStorage(storage);
++ const draft = {
++ title: "Private note",
++ content: "Only user one can read this",
++ saved: null,
++ };
++
++ saveChatMarkdownNoteDraft("user-1", "session-1", draft, noteStorage);
++
++ assert.deepEqual(
++ loadChatMarkdownNoteDraft("user-2", "session-1", noteStorage),
++ { title: "", content: "", saved: null },
++ );
++ assert.deepEqual(
++ loadChatMarkdownNoteDraft("user-1", "session-1", noteStorage),
++ draft,
++ );
++});
++
+ function createStorage(
+ values: Map<string, string>,
-): Parameters<typeof saveChatMarkdownNoteDraft>[2] {
++): Parameters<typeof saveChatMarkdownNoteDraft>[3] {
+ return {
+ getItem(key) {
+ return values.get(key) ?? null;
+ },
+ setItem(key, value) {
+ values.set(key, value);
+ },
+ removeItem(key) {
+ values.delete(key);
+ },
+ };
+ }