import { memo, useCallback, useEffect, useState } from 'react'; import type { SessionPendingInteraction } from '@deepseek-ai/dsh-client-ui-session/client'; import type { SessionId } from '@deepseek-ai/dsh-session/types'; import { OFFICIAL_SEATS } from './official-slots.js'; import type { ReaderInjected, ReaderProps } from './types.js'; import { answerDisplayValues, formatQuestionFollowUpReply, type QuestionAnswerItem, type QuestionItem, type TurnQuestionEntry, type TurnQuestionStatus, } from './turn-questions.js'; import css from './Reader.module.css'; interface QuestionDraft { readonly id: string; readonly selected: string[]; readonly custom: string; } interface PendingQuestionSnapshotView { readonly state?: string; readonly channel?: string; readonly closed?: boolean; readonly countdown?: { readonly remainingMs: number; readonly running: boolean; }; } export interface InteractivePendingQuestion { readonly key: string; readonly kind: string; readonly questions?: readonly QuestionItem[]; readonly review?: readonly QuestionAnswerItem[]; answer(payload: { answers: QuestionAnswerItem[] }): Promise; dismiss?(): Promise; snapshot?(): PendingQuestionSnapshotView; getSnapshot?(): PendingQuestionSnapshotView; subscribe?(listener: () => void): () => void; holdFocus?(): void; releaseFocus?(): void; engage?(): void; } export function asInteractivePending( pending: SessionPendingInteraction | undefined, ): InteractivePendingQuestion | undefined { if (!pending || pending.kind !== 'question') return undefined; const candidate = pending as unknown as Partial; if (typeof candidate.answer !== 'function') return undefined; if (candidate.review !== undefined) return undefined; return candidate as InteractivePendingQuestion; } function buildInitialDrafts( questions: readonly QuestionItem[], answers: readonly QuestionAnswerItem[], ): QuestionDraft[] { const byId = new Map(answers.map(item => [item.id, item])); return questions.map(question => { const prev = byId.get(question.id); return { id: question.id, selected: prev ? [...prev.selected] : [], custom: prev?.custom ?? '', }; }); } function statusBadgeLabel(status: TurnQuestionStatus): string { switch (status) { case 'open': return '待回答'; case 'continued': return '已继续工作 · 仍可回答'; case 'queued': return '回答已排队 · 等待接收'; case 'answered': return '已回答'; case 'cancelled': return '已取消'; case 'interrupted': return '已中断'; case 'closed': return '未作答'; } } function summaryLineForEntry(entry: TurnQuestionEntry): string { const first = entry.questions[0]; if (!first) return statusBadgeLabel(entry.status); const title = first.header && first.header !== first.question ? first.header : first.question; const firstAnswer = entry.answers.find(item => item.id === first.id); const values = answerDisplayValues(firstAnswer); const tail = entry.questions.length > 1 ? ` · 共 ${entry.questions.length} 题` : ''; if (entry.status === 'answered' || entry.status === 'queued') { const answerText = values.length > 0 ? values.join('、') : '已跳过'; return `${title}:${answerText}${tail}`; } return `${title}${tail}`; } export const HostedOfficialQuestion = memo(function HostedOfficialQuestion({ callId, sessionId, pending, useSession, renderSlotChain, }: { callId: string; sessionId: SessionId; pending: SessionPendingInteraction; useSession: ReaderProps['useSession']; renderSlotChain: ReaderProps['renderSlotChain']; }) { const session = useSession(snapshot => snapshot); const fallback = (
需要你回答一个问题 请在下方原生操作区处理。此提示不会收进执行过程。
); return (
{renderSlotChain(OFFICIAL_SEATS.composer, { sessionId, session, pendingInteraction: pending, }, { fallback })}
); }); /** * Native Muse-style flat-in-bubble UI for live pending `ask_user_question` interactions. * Single-question single-select options render as full-width dashed buttons that * submit on one click directly inside the AI reply bubble. */ export const MuseLiveQuestion = memo(function MuseLiveQuestion({ callId, pending, fallbackQuestions, }: { callId: string; pending: InteractivePendingQuestion; fallbackQuestions?: readonly QuestionItem[]; }) { const questions = (pending.questions && pending.questions.length > 0) ? pending.questions : (fallbackQuestions ?? []); const [step, setStep] = useState(0); const [drafts, setDrafts] = useState(() => buildInitialDrafts(questions, [])); const [customOpen, setCustomOpen] = useState(false); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); const [snapshot, setSnapshot] = useState( () => pending.snapshot?.() ?? pending.getSnapshot?.() ?? {}, ); useEffect(() => { const sync = () => { setSnapshot(pending.snapshot?.() ?? pending.getSnapshot?.() ?? {}); }; sync(); return pending.subscribe?.(sync); }, [pending]); useEffect(() => { setDrafts(current => { if ( current.length === questions.length && current.every((item, idx) => item.id === questions[idx]?.id) ) { return current; } return buildInitialDrafts(questions, []); }); setStep(current => (questions.length > 0 ? Math.min(current, questions.length - 1) : 0)); }, [questions]); useEffect(() => () => { pending.releaseFocus?.(); }, [pending]); const submitPayload = useCallback(async (answers: QuestionAnswerItem[]) => { if (submitting) return; setSubmitting(true); setError(null); try { const channel = (pending.snapshot?.() ?? pending.getSnapshot?.())?.channel; await pending.answer({ answers }); if (channel === 'rpc') { await pending.dismiss?.(); } } catch (cause) { setError(cause instanceof Error ? cause.message : '提交回答失败,请重试。'); } finally { setSubmitting(false); } }, [submitting, pending]); const activeIndex = Math.min(step, Math.max(0, questions.length - 1)); const currentQuestion = questions[activeIndex]; if (!currentQuestion) return null; const isSingleQuickPick = questions.length === 1 && currentQuestion.multiSelect !== true && (currentQuestion.options?.length ?? 0) > 0; const draft = drafts[activeIndex] ?? { id: currentQuestion.id, selected: [], custom: '' }; const channelReady = snapshot.channel !== 'none'; const remainingSec = snapshot.countdown?.running ? Math.ceil(snapshot.countdown.remainingMs / 1000) : undefined; const handleOptionClick = (label: string) => { if (submitting || !channelReady) return; pending.engage?.(); setError(null); if (isSingleQuickPick && !customOpen) { void submitPayload([{ id: currentQuestion.id, selected: [label] }]); return; } const multi = currentQuestion.multiSelect === true; const nextDrafts = drafts.map((item, idx) => { if (idx !== activeIndex) return item; if (multi) { const exists = item.selected.includes(label); return { ...item, selected: exists ? item.selected.filter(x => x !== label) : [...item.selected, label], }; } const already = item.selected.length === 1 && item.selected[0] === label; return { ...item, selected: already ? [] : [label], custom: '' }; }); setDrafts(nextDrafts); if (!multi && activeIndex < questions.length - 1) { setStep(activeIndex + 1); } }; const handleSubmitDrafts = () => { const answers: QuestionAnswerItem[] = questions.map((item, idx) => { const value = drafts[idx] ?? { id: item.id, selected: [], custom: '' }; const custom = value.custom.trim(); return { id: item.id, selected: custom === '' || item.multiSelect === true ? [...value.selected] : [], ...(custom !== '' ? { custom } : {}), }; }); const missingIndex = answers.findIndex( item => item.selected.length === 0 && (item.custom?.length ?? 0) === 0, ); if (missingIndex >= 0) { setStep(missingIndex); setError('请先选择选项或输入自定义回答。'); return; } void submitPayload(answers); }; const showSubmitBar = !isSingleQuickPick || customOpen; return (
{ pending.holdFocus?.(); }} onMouseLeave={() => { pending.releaseFocus?.(); }} onFocusCapture={() => { pending.holdFocus?.(); }} onBlurCapture={event => { if (!event.currentTarget.contains(event.relatedTarget)) { pending.releaseFocus?.(); } }} > {questions.length > 1 && (
{questions.map((item, idx) => { const done = (drafts[idx]?.selected.length ?? 0) > 0 || (drafts[idx]?.custom.trim().length ?? 0) > 0; return ( ); })}
)}
{currentQuestion.header && currentQuestion.header !== currentQuestion.question && questions.length === 1 && ( {currentQuestion.header} )} {currentQuestion.question} {currentQuestion.multiSelect === true && 多选} {remainingSec !== undefined && ( {`${remainingSec}s`} )}
{currentQuestion.options && currentQuestion.options.length > 0 && (
{currentQuestion.options.map(option => { const selected = draft.selected.includes(option.label); return ( ); })}
)} {(customOpen || (currentQuestion.options?.length ?? 0) === 0) && ( { pending.engage?.(); setError(null); const value = event.target.value; setDrafts(current => current.map((item, idx) => ( idx === activeIndex ? { ...item, custom: value, selected: currentQuestion.multiSelect ? item.selected : [] } : item ))); }} onKeyDown={event => { if (event.key === 'Enter' && (!isSingleQuickPick || event.ctrlKey || event.metaKey || valueOrSubmitReady(draft))) { if (!currentQuestion.multiSelect && questions.length === 1 && draft.custom.trim()) { event.preventDefault(); handleSubmitDrafts(); } } }} /> )} {error &&

{error}

}
{(currentQuestion.options?.length ?? 0) > 0 && ( )}
{showSubmitBar && (
{activeIndex > 0 && ( )} {activeIndex < questions.length - 1 ? ( ) : ( )}
)}
); }); function valueOrSubmitReady(draft: QuestionDraft): boolean { return draft.selected.length > 0 || draft.custom.trim().length > 0; } export interface TurnQuestionCardProps { entry: TurnQuestionEntry; sessionId: SessionId; pending: SessionPendingInteraction | undefined; inlineClaimed: boolean; useSession: ReaderProps['useSession']; renderSlotChain: ReaderProps['renderSlotChain']; revealQuestion?: ReaderInjected['revealQuestion']; reviewQuestion?: ReaderInjected['reviewQuestion']; answerContinuedQuestion?: ReaderInjected['answerContinuedQuestion']; sendFollowUp?: ReaderInjected['sendFollowUp']; fillComposer?: ReaderInjected['fillComposer']; } export const TurnQuestionCard = memo(function TurnQuestionCard({ entry, sessionId, pending, inlineClaimed, useSession, renderSlotChain, revealQuestion, reviewQuestion, answerContinuedQuestion, sendFollowUp, fillComposer, }: TurnQuestionCardProps) { const [formOpen, setFormOpen] = useState(false); const [customOpen, setCustomOpen] = useState(false); const [detailsOpen, setDetailsOpen] = useState(false); const [drafts, setDrafts] = useState(() => buildInitialDrafts(entry.questions, entry.answers), ); const [submitting, setSubmitting] = useState(false); const [formError, setFormError] = useState(null); useEffect(() => { if (entry.status === 'queued' || entry.status === 'answered') { setFormOpen(false); setCustomOpen(false); setFormError(null); } }, [entry.status]); const openForm = useCallback(() => { setDrafts(buildInitialDrafts(entry.questions, entry.answers)); setFormError(null); setDetailsOpen(false); setFormOpen(true); }, [entry.questions, entry.answers]); const submitPayload = useCallback(async (payload: QuestionAnswerItem[]) => { if (submitting) return; setSubmitting(true); setFormError(null); try { if (entry.status === 'continued' && answerContinuedQuestion) { const accepted = await answerContinuedQuestion(entry.callId, payload); if (accepted) { setFormOpen(false); setCustomOpen(false); return; } } const mode = entry.status === 'answered' ? 'revise' : 'answer'; const text = formatQuestionFollowUpReply(entry.questions, payload, mode); if (sendFollowUp && await sendFollowUp(text)) { setFormOpen(false); setCustomOpen(false); return; } if (fillComposer?.(text)) { setFormOpen(false); setCustomOpen(false); return; } setFormError('暂时无法提交回答,请稍后再试。'); } catch { setFormError('暂时无法提交回答,请稍后再试。'); } finally { setSubmitting(false); } }, [submitting, entry.status, entry.callId, entry.questions, answerContinuedQuestion, sendFollowUp, fillComposer]); const toggleOption = useCallback(( question: QuestionItem, label: string, quickSubmitSingle: boolean, ) => { if (submitting) return; setFormError(null); if (quickSubmitSingle && !customOpen) { void submitPayload([{ id: question.id, selected: [label] }]); return; } const multi = question.multiSelect === true; setDrafts(current => current.map(draft => { if (draft.id !== question.id) return draft; if (multi) { const exists = draft.selected.includes(label); return { ...draft, selected: exists ? draft.selected.filter(item => item !== label) : [...draft.selected, label], }; } const alreadyOnly = draft.selected.length === 1 && draft.selected[0] === label; return { ...draft, selected: alreadyOnly ? [] : [label], }; })); }, [submitting, customOpen, submitPayload]); const updateCustom = useCallback((questionId: string, custom: string) => { setFormError(null); setDrafts(current => current.map(draft => ( draft.id === questionId ? { ...draft, custom } : draft ))); }, []); const buildPayload = useCallback((): QuestionAnswerItem[] | null => { const items: QuestionAnswerItem[] = drafts.map(draft => { const custom = draft.custom.trim(); return { id: draft.id, selected: [...draft.selected], ...(custom.length > 0 ? { custom } : {}), }; }); const hasAny = items.some(item => item.selected.length > 0 || (item.custom?.length ?? 0) > 0); if (!hasAny) { setFormError('请至少选择一个选项或填写自定义回答。'); return null; } return items; }, [drafts]); const followUpMode = entry.status === 'answered' ? 'revise' : 'answer'; const handleFillComposer = useCallback(() => { const payload = buildPayload(); if (!payload) return; const text = formatQuestionFollowUpReply(entry.questions, payload, followUpMode); if (fillComposer?.(text)) { setFormOpen(false); } else { setFormError('未能写入底部输入框,请稍后重试。'); } }, [buildPayload, entry.questions, followUpMode, fillComposer]); const handleSubmit = useCallback(async () => { const payload = buildPayload(); if (!payload) return; await submitPayload(payload); }, [buildPayload, submitPayload]); // 1. Active pending interaction: prefer native Muse bubble layout; fall back to slot host if needed. if (pending !== undefined && inlineClaimed) { const interactive = asInteractivePending(pending); if (interactive) { return ( ); } return ( ); } const isActive = entry.status === 'open' || entry.status === 'continued'; const isQueued = entry.status === 'queued'; const answersById = new Map(entry.answers.map(item => [item.id, item])); const isQuickSingleActive = isActive && entry.questions.length === 1 && entry.questions[0]?.multiSelect !== true && (entry.questions[0]?.options?.length ?? 0) > 0; // 2. Active/continued unanswered question inside the bubble: show Muse dashed options directly! if (isActive && entry.questions.length > 0) { const useFormDraft = !isQuickSingleActive || customOpen; return (
{entry.questions.map(question => { const draft = drafts.find(item => item.id === question.id) ?? { id: question.id, selected: [], custom: '', }; const multi = question.multiSelect === true; return (
{question.header && question.header !== question.question && ( {question.header} )} {question.question} {multi && 多选} {statusBadgeLabel(entry.status)}
{question.options && question.options.length > 0 && (
{question.options.map(option => { const selected = useFormDraft && draft.selected.includes(option.label); return ( ); })}
)} {(customOpen || (question.options?.length ?? 0) === 0) && ( { updateCustom(question.id, event.target.value); }} onKeyDown={event => { if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void handleSubmit(); } }} /> )}
); })} {formError &&

{formError}

}
{useFormDraft && (
)}
); } // 3. Settled/queued/cancelled/interrupted historical question inside the bubble. return (
{entry.questions.length > 0 && !isQueued ? ( ) : (
{statusBadgeLabel(entry.status)} {summaryLineForEntry(entry)}
)}
{!isQueued && entry.reviewRecord !== undefined && reviewQuestion !== undefined && ( )} {!isQueued && entry.questions.length > 0 && ( )}
{!formOpen && (detailsOpen || isQueued) && entry.questions.length > 0 && (
{entry.questions.map(question => { const values = answerDisplayValues(answersById.get(question.id)); return (
{question.header && question.header !== question.question && ( {question.header} )} {question.question}
{values.length > 0 ? values.join(' · ') : question.options && question.options.length > 0 ? `可选项:${question.options.map(opt => opt.label).join(' / ')}` : '(未填写)'}
); })}
)} {formOpen && (
{entry.questions.map(question => { const draft = drafts.find(item => item.id === question.id) ?? { id: question.id, selected: [], custom: '', }; const multi = question.multiSelect === true; return (
{question.header && question.header !== question.question && ( {question.header} )} {question.question} {multi && 多选}
{question.options && question.options.length > 0 && (
{question.options.map(option => { const selected = draft.selected.includes(option.label); return ( ); })}
)} { updateCustom(question.id, event.target.value); }} onKeyDown={event => { if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); void handleSubmit(); } }} />
); })} {formError &&

{formError}

}
)}
); });