Files

820 lines
25 KiB
TypeScript

import { useI18n, usePageData } from '@rspress/core/runtime';
import { Link } from '@rspress/core/theme-original';
import { type ReactNode, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import ReactMarkdown, { type Components } from 'react-markdown';
import remarkGfm from 'remark-gfm';
import type { Paragraph, PhrasingContent, Root, RootContent } from 'mdast';
import './DocsAssistant.scss';
interface Citation {
citationId: string;
title: string;
url: string;
snippet: string;
verificationStatus: string;
}
interface AnswerResponse {
continuationId?: string;
requestId: string;
status:
| 'answered'
| 'insufficient_evidence'
| 'clarification_required'
| 'refused';
answer: string;
steps: string[];
appliesWhen: string[];
citations: Citation[];
missingInformation: string[];
followUpQuestion?: string;
indexVersion: string;
degraded: boolean;
}
interface DocsAssistantI18n {
docsAiOpen: string;
docsAiTitle: string;
docsAiClose: string;
docsAiQuestionPlaceholder: string;
docsAiSubmit: string;
docsAiQuestionLabel: string;
docsAiElapsed: string;
docsAiReviewing: string;
docsAiLoading: string;
docsAiProgressCallingModel: string;
docsAiProgressParsingCitations: string;
docsAiProgressVerifyingSources: string;
docsAiProgressSourcesVerified: string;
docsAiProgressRetrying: string;
docsAiSources: string;
docsAiCopy: string;
docsAiCopied: string;
docsAiCopyManually: string;
docsAiAppliesWhen: string;
docsAiFollowUpHint: string;
searchPlaceholderText: string;
docsAiSuggestionOne: string;
docsAiSuggestionTwo: string;
docsAiSuggestionThree: string;
docsAiError: string;
docsAiRequestId: string;
docsAiEmptyQuestion: string;
docsAiContextExpired: string;
}
interface AnswerProgress {
type: 'progress';
stage: string;
source_count?: number;
source_title?: string;
message: string;
attempt?: number;
maxAttempts?: number;
}
type AnswerStreamMessage =
| AnswerProgress
| { type: 'answer'; data: AnswerResponse }
| { type: 'error'; message: string; requestId: string };
const CONFIGURED_API_BASE_URL = import.meta.env.DOCS_AI_API_URL.replace(
/\/$/,
'',
);
const SITE_ORIGIN = import.meta.env.DOCS_SITE_ORIGIN;
const SITE_HOST = new URL(SITE_ORIGIN).hostname;
// The docs-ai-service backend may still return citations on the legacy hosts; they use the same routes as the current v2 site.
const LEGACY_DOCS_HOSTS = new Set([
'docs.nocobase.com',
'v2.docs.nocobase.com',
]);
interface ChatTurn {
question: string;
startedAt: number;
progress?: AnswerProgress;
answer?: AnswerResponse;
error?: string;
errorRequestId?: string;
}
export function DocsAssistant() {
const [open, setOpen] = useState(false);
const [question, setQuestion] = useState('');
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [loading, setLoading] = useState(false);
const latestTurnRef = useRef<HTMLDivElement>(null);
const continuationRef = useRef<string>();
const textareaRef = useRef<HTMLTextAreaElement>(null);
const abortRef = useRef<AbortController>();
const t = useI18n<DocsAssistantI18n>();
const {
page: { lang, version },
} = usePageData();
useEffect(() => {
if (open) {
textareaRef.current?.focus();
}
document.documentElement.classList.toggle('docs-ai-workspace-open', open);
return () => {
document.documentElement.classList.remove('docs-ai-workspace-open');
};
}, [open]);
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape' && open) {
setOpen(false);
}
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [open]);
useEffect(() => () => abortRef.current?.abort(), []);
useLayoutEffect(() => {
if (open) latestTurnRef.current?.scrollIntoView({ block: 'start', behavior: 'instant' });
}, [open, turns.length]);
const submit = async (suggestedQuestion?: string) => {
const nextQuestion = (suggestedQuestion ?? question).trim();
if (!nextQuestion || abortRef.current) return;
const controller = new AbortController();
abortRef.current = controller;
const turnIndex = turns.length;
const updateTurn = (update: (turn: ChatTurn) => ChatTurn) => {
setTurns((current) =>
current.map((turn, index) =>
index === turnIndex ? update(turn) : turn,
),
);
};
const startedAt = Date.now();
setQuestion('');
setTurns((current) => [
...current,
{ question: nextQuestion, startedAt },
]);
setLoading(true);
try {
const response = await fetch(`${apiBaseUrl()}/v2/answers/stream`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Docs-AI-Session': docsAiSessionId(),
},
body: JSON.stringify({
question: nextQuestion,
previousAnswerId: continuationRef.current,
language: normalizeLanguage(lang),
productVersion: version || 'current',
currentPage: window.location.href,
}),
signal: controller.signal,
});
const responseRequestId = response.headers.get('x-request-id') ?? '';
if (response.status === 409) {
continuationRef.current = undefined;
updateTurn((turn) => ({ ...turn, error: t('docsAiContextExpired') }));
return;
}
if (!response.ok) {
throw new DocsAssistantRequestError(responseRequestId);
}
const nextAnswer = await readAnswerStream(response, (event) => {
updateTurn((turn) => ({
...turn,
progress: event,
}));
});
if (nextAnswer.continuationId)
continuationRef.current = nextAnswer.continuationId;
updateTurn((turn) => ({ ...turn, answer: nextAnswer, progress: undefined }));
} catch (requestError) {
if (
requestError instanceof DOMException &&
requestError.name === 'AbortError'
) {
return;
}
updateTurn((turn) => ({
...turn,
error: t('docsAiError'),
errorRequestId:
requestError instanceof DocsAssistantRequestError
? requestError.requestId
: undefined,
}));
} finally {
if (abortRef.current === controller) {
abortRef.current = undefined;
setLoading(false);
}
}
};
return (
<>
{!open ? (
<button
type="button"
className="docs-ai-launcher"
aria-haspopup="dialog"
aria-expanded={false}
onClick={() => setOpen(true)}
>
<SparklesIcon />
{t('docsAiOpen')}
</button>
) : null}
{open ? (
<aside
className="docs-ai-panel"
role="dialog"
aria-modal="false"
aria-labelledby="docs-ai-title"
>
<header className="docs-ai-header">
<div className="docs-ai-heading">
<SparklesIcon />
<h2 id="docs-ai-title">{t('docsAiTitle')}</h2>
</div>
<div className="docs-ai-header-actions">
<button
type="button"
className="docs-ai-icon-button"
aria-label={t('searchPlaceholderText')}
onClick={() => {
const trigger = document.querySelector<HTMLButtonElement>('.rp-nav .rp-search-button');
if (trigger) {
setOpen(false);
trigger.click();
}
}}
>
<svg aria-hidden="true" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="7.5" /><path d="m16 16 5 5" /></svg>
</button>
<button
type="button"
className="docs-ai-icon-button"
aria-label={t('docsAiClose')}
onClick={() => {
setOpen(false);
}}
>
<CloseIcon />
</button>
</div>
</header>
<div
className="docs-ai-body"
role="log"
aria-live="polite"
onClick={(event) => {
if (
event.button === 0 &&
!event.metaKey &&
!event.ctrlKey &&
!event.shiftKey &&
!event.altKey &&
event.target instanceof Element &&
event.target.closest('a[href]') &&
window.matchMedia('(max-width: 640px)').matches
) {
setOpen(false);
}
}}
>
{turns.length === 0 ? (
<section
className="docs-ai-welcome"
aria-labelledby="docs-ai-suggestions-title"
>
<span className="docs-ai-welcome-mark"><SparklesIcon /></span>
<h3 id="docs-ai-suggestions-title">{t('docsAiQuestionPlaceholder')}</h3>
<div className="docs-ai-suggestions">
{[
t('docsAiSuggestionOne'),
t('docsAiSuggestionTwo'),
t('docsAiSuggestionThree'),
].map((suggestion) => (
<button
key={suggestion}
type="button"
onClick={() => submit(suggestion)}
>
{suggestion}
<svg aria-hidden="true" viewBox="0 0 24 24"><path d="M6 18 18 6M7 6h11v11" /></svg>
</button>
))}
</div>
</section>
) : null}
{turns.map(
(
{
question: submittedQuestion,
progress,
startedAt,
answer,
error,
errorRequestId,
},
index,
) => (
<div
className="docs-ai-turn"
key={index}
ref={index === turns.length - 1 ? latestTurnRef : undefined}
>
<section
className="docs-ai-submitted-question"
aria-label={t('docsAiQuestionLabel')}
>
<p>{submittedQuestion}</p>
</section>
{loading &&
index === turns.length - 1 &&
!answer &&
!error ? (
<RetrievalProgress startedAt={startedAt} progress={progress} t={t} />
) : null}
{error ? (
<p className="docs-ai-error">
{error}
{errorRequestId ? (
<small>
{t('docsAiRequestId')}: {errorRequestId}
</small>
) : null}
</p>
) : null}
{answer ? <AnswerView answer={answer} t={t} /> : null}
</div>
),
)}
</div>
<footer className="docs-ai-footer">
<p className="docs-ai-hint">{t('docsAiFollowUpHint')}</p>
<form
className="docs-ai-form"
onSubmit={(event) => {
event.preventDefault();
submit();
}}
>
<textarea
ref={textareaRef}
value={question}
maxLength={500}
rows={2}
placeholder={t('docsAiQuestionPlaceholder')}
aria-label={t('docsAiQuestionPlaceholder')}
onChange={(event) => setQuestion(event.target.value)}
onKeyDown={(event) => {
if (
event.key === 'Enter' &&
!event.shiftKey &&
!event.nativeEvent.isComposing
) {
event.preventDefault();
submit();
}
}}
/>
<button
type="submit"
aria-label={t('docsAiSubmit')}
disabled={loading || !question.trim()}
>
<ArrowUpIcon />
</button>
</form>
</footer>
</aside>
) : null}
</>
);
}
function SparklesIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 24 24" focusable="false">
<path d="M12 2.8c.8 4.5 3.1 6.8 7.6 7.6-4.5.8-6.8 3.1-7.6 7.6-.8-4.5-3.1-6.8-7.6-7.6C8.9 9.6 11.2 7.3 12 2.8Z" />
<path d="M5 2.5c.25 1.45 1.05 2.25 2.5 2.5C6.05 5.25 5.25 6.05 5 7.5 4.75 6.05 3.95 5.25 2.5 5 3.95 4.75 4.75 3.95 5 2.5Z" />
</svg>
);
}
function CloseIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 24 24" focusable="false">
<path d="M5 5l14 14M19 5 5 19" />
</svg>
);
}
function ArrowUpIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 24 24" focusable="false">
<path d="M12 19V5m-6 6 6-6 6 6" />
</svg>
);
}
function AnswerView({
answer,
t,
}: {
answer: AnswerResponse;
t: ReturnType<typeof useI18n<DocsAssistantI18n>>;
}) {
const safeCitations = answer.citations.filter((citation) =>
isOfficialDocsUrl(citation.url),
);
const sourceLabel = t('docsAiSources');
const verified = useMemo(
() =>
new Map(
answer.citations
.filter(
(item) =>
isOfficialDocsUrl(item.url) &&
(item.verificationStatus === 'index_verified' ||
item.verificationStatus === 'live_verified'),
)
// Markdown encodes non-ASCII fragments when rendering an anchor.
.flatMap((item) => [
[item.url, item] as const,
[new URL(item.url).href, item] as const,
]),
),
[answer.citations],
);
const paragraphSources = useMemo(
() => () => (tree: Root) => {
function isMarker(node: PhrasingContent) {
return (
node.type === 'link' &&
node.children.length === 1 &&
node.children[0].type === 'text' &&
node.children[0].value === 'source'
);
}
function appendSource(paragraph: Paragraph, source: PhrasingContent) {
const last = paragraph.children[paragraph.children.length - 1];
// Keep a short tail of prose and its icon on the same line.
const tail = last?.type === 'text' &&
last.value.trimEnd().match(/(?:[\p{Script=Latin}\d]+|[^\s])\p{P}*$/u);
if (last?.type === 'text' && tail) {
last.value = last.value.slice(0, tail.index);
paragraph.children.push({
type: 'emphasis',
data: { hName: 'span', hProperties: { className: 'docs-ai-source-tail' } },
children: [{ type: 'text', value: tail[0] }, source],
});
} else {
paragraph.children.push(source);
}
}
let uncitedParagraph: Paragraph | undefined;
function visit(node: Root | RootContent) {
if (node.type === 'paragraph') {
const source = node.children.find(
(child) => isMarker(child) && child.type === 'link' && verified.has(child.url),
);
node.children = node.children.filter((child) => !isMarker(child));
const hasProse = node.children.some((child) => child.type !== 'text' || child.value.trim());
if (hasProse) uncitedParagraph = node;
// Models sometimes put a command's citation alone below its fence.
if (source && uncitedParagraph) {
appendSource(uncitedParagraph, source);
uncitedParagraph = undefined;
}
} else if ('children' in node) {
if (node.type === 'heading' || node.type === 'listItem') uncitedParagraph = undefined;
node.children.forEach(visit);
}
}
visit(tree);
},
[verified],
);
const components = useMemo<Components>(
() => ({
...MARKDOWN_COMPONENTS,
a({ href, children }) {
if (children === 'source') {
const citation = href && verified.get(href);
if (!citation) return null;
const label = `${sourceLabel} · ${citationTitle(citation)}`;
return (
<Link
className="docs-ai-inline-source"
href={toSitePath(citation.url)}
title={label}
aria-label={label}
/>
);
}
if (!isOfficialDocsUrl(href)) return <span>{children}</span>;
return <Link href={toSitePath(href)}>{children}</Link>;
},
}),
[verified, sourceLabel],
);
return (
<article className="docs-ai-answer">
<div className="docs-ai-answer-text">
<ReactMarkdown
components={components}
remarkPlugins={[remarkGfm, paragraphSources]}
skipHtml
>
{answer.answer}
</ReactMarkdown>
</div>
{answer.steps.length > 0 ? (
<ol>
{answer.steps.map((step) => (
<li key={step}>{step}</li>
))}
</ol>
) : null}
{answer.appliesWhen.length > 0 ? (
<div className="docs-ai-applies">
<strong>{t('docsAiAppliesWhen')}</strong>
<ul>
{answer.appliesWhen.map((condition) => (
<li key={condition}>{condition}</li>
))}
</ul>
</div>
) : null}
{safeCitations.length > 0 ? (
<details className="docs-ai-sources">
<summary>{t('docsAiSources')} ({safeCitations.length})</summary>
<ul>
{safeCitations.map((citation) => (
<li key={citation.citationId}>
<Link href={toSitePath(citation.url)}>
{citationTitle(citation)}
</Link>
</li>
))}
</ul>
</details>
) : null}
</article>
);
}
function citationTitle(citation: Citation): string {
if (citation.title && citation.title !== citation.url) {
return citation.title;
}
try {
const url = new URL(citation.url);
const segment = decodeURIComponent(
url.pathname.split('/').filter(Boolean).at(-1) ?? '',
);
return segment ? segment.replaceAll('-', ' ') : 'NocoBase 官方文档';
} catch {
return 'NocoBase 官方文档';
}
}
function CodeBlock({ children, language }: { children: ReactNode; language?: string }) {
const ref = useRef<HTMLPreElement>(null);
const [feedback, setFeedback] = useState<'docsAiCopied' | 'docsAiCopyManually'>();
const t = useI18n<DocsAssistantI18n>();
useEffect(() => {
if (!feedback) return;
const timer = window.setTimeout(() => setFeedback(undefined), 2000);
return () => window.clearTimeout(timer);
}, [feedback]);
async function copyCode() {
const pre = ref.current;
if (!pre) return;
try {
await navigator.clipboard.writeText(pre.textContent ?? '');
setFeedback('docsAiCopied');
} catch {
const range = document.createRange();
range.selectNodeContents(pre);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
setFeedback('docsAiCopyManually');
}
}
return (
<div className="docs-ai-code">
<div className="docs-ai-code-tools">
<span>{language}</span>
<button type="button" onClick={copyCode} aria-live="polite">{t(feedback ?? 'docsAiCopy')}</button>
</div>
<pre ref={ref}>{children}</pre>
</div>
);
}
const MARKDOWN_COMPONENTS: Components = {
pre({ node, children }) {
const code = node?.children[0];
const classes = code?.type === 'element' ? code.properties.className : undefined;
const language = Array.isArray(classes)
? classes.map(String).find((name) => name.startsWith('language-'))?.slice(9)
: undefined;
return <CodeBlock language={language}>{children}</CodeBlock>;
},
table({ children }) {
return <div className="docs-ai-table"><table>{children}</table></div>;
},
img() {
return null;
},
};
function isOfficialDocsUrl(value?: string): value is string {
if (!value) {
return false;
}
try {
const url = new URL(value);
return (
url.protocol === 'https:' &&
!/^\/[\\/]/.test(decodeURIComponent(url.pathname)) &&
(url.hostname === SITE_HOST || LEGACY_DOCS_HOSTS.has(url.hostname))
);
} catch {
return false;
}
}
function toSitePath(value: string): string {
const url = new URL(value);
return url.pathname + url.search + url.hash;
}
function apiBaseUrl(): string {
if (CONFIGURED_API_BASE_URL) {
return CONFIGURED_API_BASE_URL;
}
return window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1'
? 'http://127.0.0.1:3100'
: '/api/ai';
}
async function readAnswerStream(
response: Response,
onProgress: (event: AnswerProgress) => void,
): Promise<AnswerResponse> {
if (!response.body) {
throw new Error('Streaming response body is unavailable');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let answer: AnswerResponse | undefined;
const consumeLine = (line: string) => {
if (!line.trim()) {
return;
}
const event = JSON.parse(line) as AnswerStreamMessage;
if (event.type === 'progress') {
onProgress(event);
} else if (event.type === 'answer') {
answer = event.data;
} else {
throw new DocsAssistantRequestError(event.requestId);
}
};
while (true) {
const { done, value } = await reader.read();
buffer += decoder.decode(value, { stream: !done });
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
lines.forEach(consumeLine);
if (done) {
break;
}
}
consumeLine(buffer);
if (!answer) {
throw new Error('Streaming response ended without an answer');
}
return answer;
}
function normalizeLanguage(lang: string): string {
const languageMap: Readonly<Record<string, string>> = {
en: 'en-US',
cn: 'zh-CN',
zh: 'zh-CN',
ja: 'ja-JP',
es: 'es-ES',
pt: 'pt-PT',
de: 'de-DE',
fr: 'fr-FR',
ru: 'ru-RU',
id: 'id-ID',
vi: 'vi-VN',
};
return languageMap[lang.toLowerCase()] ?? 'en-US';
}
function RetrievalProgress({ startedAt, progress, t }: {
startedAt: number;
progress?: AnswerProgress;
t: ReturnType<typeof useI18n<DocsAssistantI18n>>;
}) {
const [seconds, setSeconds] = useState(() => Math.floor((Date.now() - startedAt) / 1000));
useEffect(() => {
const timer = window.setInterval(() => setSeconds(Math.floor((Date.now() - startedAt) / 1000)), 1000);
return () => window.clearInterval(timer);
}, [startedAt]);
return (
<details className="docs-retrieval" open>
<summary aria-live="off">
<span>{t('docsAiElapsed').replace('{s}', String(seconds))}</span>
<span className="docs-retrieval-count">{progress?.source_count !== undefined && `${t('docsAiSources')} (${progress.source_count})`}</span>
</summary>
{progress?.source_title && <div className="docs-retrieval-row docs-retrieval-source">{progress.source_title}</div>}
<div className="docs-retrieval-row docs-retrieval-active" role="status">
{progress ? progressMessage(progress, t) : t('docsAiLoading')}
</div>
</details>
);
}
function progressMessage(
progress: AnswerProgress,
t: ReturnType<typeof useI18n<DocsAssistantI18n>>,
): string {
const messageKeys: Readonly<Record<string, keyof DocsAssistantI18n>> = {
submitted: 'docsAiLoading',
searching_docs: 'docsAiLoading',
reviewing_evidence: 'docsAiReviewing',
calling_model: 'docsAiProgressCallingModel',
parsing_citations: 'docsAiProgressParsingCitations',
verifying_sources: 'docsAiProgressVerifyingSources',
sources_verified: 'docsAiProgressSourcesVerified',
retrying: 'docsAiProgressRetrying',
};
const key = messageKeys[progress.stage];
return key ? t(key) : progress.message;
}
const DOCS_AI_SESSION_KEY = 'nocobase-docs-ai-session';
const DOCS_AI_SESSION_ID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
function docsAiSessionId(): string {
const existing = window.sessionStorage.getItem(DOCS_AI_SESSION_KEY);
if (existing && DOCS_AI_SESSION_ID_PATTERN.test(existing)) {
return existing;
}
const sessionId = window.crypto?.randomUUID?.() ?? fallbackSessionId();
window.sessionStorage.setItem(DOCS_AI_SESSION_KEY, sessionId);
return sessionId;
}
function fallbackSessionId(): string {
const bytes = Array.from({ length: 16 }, () =>
Math.floor(Math.random() * 256),
);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = bytes.map((byte) => byte.toString(16).padStart(2, '0')).join('');
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20),
].join('-');
}
class DocsAssistantRequestError extends Error {
constructor(readonly requestId: string) {
super('Documentation assistant request failed');
this.name = 'DocsAssistantRequestError';
}
}