'use client' /** * Dito — a conversation held at one line of the page. * * The panel opens on a line (a selection, the line's own "ask" orb, a * learning block's Generate) and shows that line's conversation; closing it * folds the conversation back onto the line as an orb. It can switch to any * other conversation on the page, and the page scrolls to where that one * was held. * * The transcript is the main chat's own component, since the conversation is * an ordinary session in the shared runtime. The composer is the notebook's: * on a page Dito explains, rewrites and makes learning material in place, so * it offers that instead of chat's modes, skills and connectors. */ import './note-companion.css' import Link from 'next/link' import { usePathname } from 'next/navigation' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { ArrowUp, Check, FilePlus2, Files, Languages, Lightbulb, ListChecks, MessageSquareText, MessagesSquare, Minimize2, PenLine, Plus, Search, ShieldCheck, Sparkles, Square, TextQuote, X, AlignLeft, WandSparkles, } from 'lucide-react' import { ChatMessageList, RoughActionButton } from '@/features/chat/messages' import { useChatStateAdapter, type MessageAttachment, type MessageItem, } from '@/features/chat/ChatStateAdapter' import { buildSessionActivity } from '@/components/chat/home/SessionActivityPanel' import SessionViewerPanel, { type SessionViewerPanelHandle, } from '@/components/chat/home/SessionViewerPanel' import { ChatViewerBridges } from '@/components/chat/home/ChatViewerBridges' import ModelSelector from '@/components/chat/home/ModelSelector' import { COMMAND_CONFIRMATION_FAILED } from '@/features/chat/transport/command-delivery' import { useChatAutoScroll } from '@/hooks/useChatAutoScroll' import { useMeasuredHeight } from '@/hooks/useMeasuredHeight' import { useResearchOutlineContinuation } from '@/hooks/useResearchOutlineContinuation' import { hasPendingAskUser, REPLY_SENT_AS_NEW_MESSAGE } from '@/lib/ask-user-state' import { copyText } from '@/lib/clipboard' import { listLLMOptions, type LLMOption } from '@/lib/llm-options' import type { LLMSelection } from '@/features/chat/model/protocol' import { notify } from '@/lib/notifications' import { createNote, noteRequest, saveNote } from '@/lib/notes-api' import Tooltip from '@/shared/ui/Tooltip' import { useMenuPopover } from '@/shared/ui/useMenuPopover' import { resultLearningBlock } from '../model/results' import { LEARNING_KINDS, learningKind } from '../model/learning-kinds' import { relativeTime, type NoteThreadView } from '../model/threads' import type { NoteCompanionProps } from './note-companion-props' const COMPOSER_FADE = 'linear-gradient(to bottom, #000 calc(100% - 28px), transparent)' /** What can be made at a line from the composer; a task is not generated. */ const MAKE_KINDS = LEARNING_KINDS.filter(kind => kind.kind !== 'task') const ABOUT_SELECTION = [ { label: 'Explain this', prompt: 'Explain this passage in plain words.', Icon: Lightbulb }, { label: 'Rewrite', prompt: 'Rewrite this passage more clearly and suggest it as an edit.', Icon: PenLine, }, { label: 'Make shorter', prompt: 'Shorten this passage and suggest it as an edit.', Icon: Minimize2, }, { label: 'Give an example', prompt: 'Give a concrete example of this.', Icon: MessageSquareText }, { label: 'Translate', prompt: 'Translate this passage and suggest it as an edit.', Icon: Languages, }, { label: 'Quiz me on this', prompt: 'Ask me two questions to check I understand this.', Icon: ListChecks, }, ] const ABOUT_LINE = [ { label: 'Continue writing here', prompt: 'Continue writing from this line and suggest it as an insert.', Icon: PenLine, }, { label: 'Explain this part', prompt: 'Explain this part of my notes.', Icon: Lightbulb }, { label: 'Check the facts', prompt: 'Check the facts around this line and comment on anything wrong.', Icon: ShieldCheck, }, { label: 'Summarize this page', prompt: 'Summarize this page.', Icon: AlignLeft }, ] /** About a card on the page: a learning block, a figure, an embed. */ const ABOUT_CARD = [ { label: 'Walk me through this', prompt: 'Walk me through this block: what it shows, step by step, and why it matters.', Icon: Lightbulb, }, { label: 'Quiz me on this', prompt: 'Ask me two questions to check I understand this block.', Icon: ListChecks, }, { label: 'Improve this block', prompt: 'Fix mistakes and fill gaps in this block, and suggest the improved block as an edit.', Icon: PenLine, }, { label: 'Check the facts', prompt: 'Check the facts in this block and comment on anything wrong.', Icon: ShieldCheck, }, ] const CARD_TYPES = new Set([ 'learning', 'image', 'video', 'audio', 'file', 'webCard', 'htmlEmbed', 'math', 'clip', 'table', 'codeBlock', ]) const isCard = (kind: string | null) => !!kind && CARD_TYPES.has(kind.split(':')[0]) /** The icon a block is named with: its learning kind's, or a quote mark. */ function BlockIcon({ kind }: { kind: string | null }) { const Icon = kind?.startsWith('learning:') ? learningKind(kind.slice(9)).Icon : TextQuote return } function resultBlock(message: MessageItem) { const event = [...(message.events || [])].reverse().find(e => e.type === 'result') if (!event) return undefined const result = (event.metadata || {}) as Record return resultLearningBlock( result, String(result.response || event.content || message.content || '') ) } export default function NoteCompanion(props: NoteCompanionProps) { // Inside /chat's viewer the shared runtime is showing the conversation the // learner is in; a second thread here would switch it underneath them. const pathname = usePathname() || '' if (!pathname.startsWith('/co-writer')) return return } function EmbeddedNotice({ pageId, onClose }: NoteCompanionProps) { const { t } = useTranslation() return ( ) } function ThreadPanel({ pageId, thread, bound, threads, blockText, blockKind, focus, onAskFocus, onDismissFocus, prefill, onSend, onMake, onRegenerate, onSelect, onNewHere, onJump, onSuggestions, onClose, }: NoteCompanionProps) { const { t } = useTranslation() const { state, submitUserReply, cancelStreamingTurn, setLLMSelection, deleteTurn, editMessage, switchBranch, loadMessageTrace, releaseMessageTrace, } = useChatStateAdapter() const confirmResearchOutline = useResearchOutlineContinuation() const [error, setError] = useState('') const [savedPage, setSavedPage] = useState('') const [viewerOpen, setViewerOpen] = useState(false) const viewerPanelRef = useRef(null) const messages = useMemo(() => (bound ? state.messages : []), [bound, state.messages]) const streaming = bound && state.isStreaming const lastMessage = messages[messages.length - 1] const awaitingUserReply = hasPendingAskUser(lastMessage?.events) const current = threads.find(item => item.session_id === thread.sessionId) const anchorText = blockText(thread.blockId) /* ── What a reply can become ──────────────────────────────────────── */ const insertHere = useCallback( (message: MessageItem) => { const block = resultBlock(message) void noteRequest(`/${pageId}/suggestions`, { operation: 'insert', // After the line this conversation is about; at the end if it is gone. block_id: anchorText === null ? '' : thread.blockId, markdown: message.content, blocks: block ? [block] : undefined, explanation: t('Dito'), }) .then(() => { onSuggestions() notify(t('Added below the line for your review')) }) .catch(e => setError(String(e))) }, [anchorText, onSuggestions, pageId, t, thread.blockId] ) const saveAsSubpage = useCallback( async (message: MessageItem) => { try { const block = resultBlock(message) const doc = await createNote(t('Research notes'), pageId, message.content) if (block) await saveNote(doc.id, { blocks: [block], expected_revision: doc.revision }) setSavedPage(doc.id) } catch (err) { setError(String(err)) } }, [pageId, t] ) const replyActions = useCallback( (message: MessageItem) => ( <> insertHere(message)} /> void saveAsSubpage(message)} /> ), [insertHere, saveAsSubpage, t] ) const submit = useCallback( (content: string, make: string | null, again = false) => { setError('') setSavedPage('') if (make) { onMake(make, content, again) return } // A turn paused on a question: what was typed is the answer. if (awaitingUserReply) { void submitUserReply({ text: content }) .then(sent => { if (sent) return notify(t(REPLY_SENT_AS_NEW_MESSAGE)) onSend(content) }) .catch(() => notify(t(COMMAND_CONFIRMATION_FAILED), { tone: 'error' })) return } onSend(content) }, [awaitingUserReply, onMake, onSend, submitUserReply, t] ) /* ── Transcript scrolling: /chat's pin-to-bottom ──────────────────── */ const { ref: composerBoxRef, height: composerHeight } = useMeasuredHeight() const { containerRef, endRef, shouldAutoScrollRef, handleScroll } = useChatAutoScroll({ hasMessages: messages.length > 0, isStreaming: streaming, composerHeight, messageCount: messages.length, lastMessageContent: lastMessage?.content, lastEventCount: lastMessage?.events?.length, }) useEffect(() => { if (!streaming) return shouldAutoScrollRef.current = true const el = containerRef.current if (el) el.scrollTop = el.scrollHeight }, [containerRef, shouldAutoScrollRef, streaming]) const activity = useMemo(() => buildSessionActivity(messages), [messages]) const quote = thread.quote || anchorText || '' const anchorKind = blockKind(thread.blockId) const starters = thread.quote ? ABOUT_SELECTION : isCard(anchorKind) ? ABOUT_CARD : ABOUT_LINE const focusText = focus ? blockText(focus) : null const focusTarget = focus && focusText !== null ? { label: focusText || t('Empty line'), kind: blockKind(focus) } : null // Opened from a block's "Regenerate…": the first make is that block again. const [make, setMake] = useState(thread.regenerate?.kind ?? null) const [again, setAgain] = useState(Boolean(thread.regenerate)) return ( ) } /** Every conversation on the page; picking one scrolls the page to its line. */ function ThreadSwitcher({ threads, currentId, blockText, onSelect, }: { threads: NoteThreadView[] currentId: string | null blockText: (blockId: string) => string | null onSelect: (sessionId: string) => void }) { const { t, i18n } = useTranslation() const [open, setOpen] = useState(false) const [query, setQuery] = useState('') const menu = useMenuPopover(open, value => { setOpen(value) if (!value) setQuery('') }) const needle = query.trim().toLowerCase() const rows = [...threads] .sort((a, b) => b.updated_at - a.updated_at) .filter( thread => !needle || [thread.label, thread.quote, thread.last_message, blockText(thread.block_id) || ''] .join(' ') .toLowerCase() .includes(needle) ) // Positioned against the panel header, not the button: the list must fit // inside the panel whatever sits to the button's right. return (
{open && (
{rows.map(thread => { const line = blockText(thread.block_id) return ( ) })} {!rows.length && (

{t( threads.length ? 'No matching conversations' : 'No conversations on this page yet' )}

)}
)}
) } /** The notebook's composer: say what you want here, or make something here. */ function ThreadComposer({ disabled, streaming, awaitingUserReply, hasQuote, aboutCard, focus, onAskFocus, onDismissFocus, prefill, make, again, onMake, llmSelection, onLLMSelectionChange, onSubmit, onStop, }: { disabled: boolean streaming: boolean awaitingUserReply: boolean hasQuote: boolean aboutCard: boolean focus: { label: string; kind: string | null } | null onAskFocus: (draft: string) => void onDismissFocus: () => void prefill: { id: number; text: string } | null make: string | null /** The make fills the block being regenerated, not a new one below. */ again: boolean onMake: (kind: string | null) => void llmSelection: LLMSelection | null onLLMSelectionChange: (value: LLMSelection | null) => void onSubmit: (content: string, make: string | null) => void onStop: () => void }) { const { t } = useTranslation() const [text, setText] = useState('') const input = useRef(null) const [menuOpen, setMenuOpen] = useState(false) const menu = useMenuPopover(menuOpen, setMenuOpen) const [options, setOptions] = useState([]) const [activeDefault, setActiveDefault] = useState(null) const [optionsState, setOptionsState] = useState<'loading' | 'error' | 'ready'>('loading') const fetchOptions = useCallback( () => listLLMOptions() .then(payload => { setOptions(payload.options) setActiveDefault(payload.active) setOptionsState('ready') }) .catch(() => setOptionsState('error')), [] ) useEffect(() => { void fetchOptions() }, [fetchOptions]) // A prompt handed over from the page lands in the box once, to be finished. const [prefilled, setPrefilled] = useState(null) if (prefill && prefill.id !== prefilled) { setPrefilled(prefill.id) setText(prefill.text) } useEffect(() => { if (prefill) requestAnimationFrame(() => input.current?.focus()) }, [prefill]) useEffect(() => { if (!disabled) requestAnimationFrame(() => input.current?.focus({ preventScroll: true })) }, [disabled]) useEffect(() => { if (make) input.current?.focus() }, [make]) // Grow with the text up to a third of the panel. useEffect(() => { const el = input.current if (!el) return el.style.height = 'auto' el.style.height = `${Math.min(el.scrollHeight, 220)}px` }, [text]) const target = make ? learningKind(make) : null const canSend = !disabled && (text.trim().length > 0 || Boolean(make)) && (!streaming || awaitingUserReply) const submit = () => { if (!canSend) return onSubmit(text.trim(), make) setText('') } return (
{focus && !target && (
)} {target && (
{again ? t('Regenerate this {{kind}}', { kind: t(target.label) }) : t('Make a {{kind}} below this line', { kind: t(target.label) })}
)}