'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 (