Files
breakpilot-compliance/admin-compliance/components/sdk/advisor/useAdvisorStream.ts
T
Benjamin Admin 49171e841f feat(advisor): Evidence Workspace — structured panes, markdown, sources as knowledge units
Rebuilds the Compliance Advisor floating widget from a plain chat into an Evidence
Workspace: pinned last question, markdown-rendered answer (clean prose), and separate
panes for Sources (hierarchical Knowledge Units), Figures (C8, conditional) and
Footnotes (C-FN), plus a stats bar (Quellen/Regelwerke/Diagramme/Fußnoten). Scrollable
turn history; stays a floating icon on every SDK page.

Architecture (user direction): the frontend renders ONLY structured evidence and NEVER
parses the answer text. The proxy now returns a JSON AdvisorEvidenceMeta line followed
by the streamed markdown answer; advisor-rag exposes structured results; an adapter maps
RAG/compiler output to the frontend envelope. Figures/footnotes wire in once the
RAG-ingestion contract lands (requested on the board) — figures pane is conditional.

- lib/sdk/advisor/{evidence,evidence-adapter}.ts (+ adapter test, 7 cases)
- components/sdk/advisor/* panes + in-house safe Markdown (no new dep, no dangerouslySetInnerHTML) + test
- useAdvisorStream (meta-line parse + streamed answer) + useAdvisorEmail (escaped)
- proxy: evidence-meta-v1 envelope + clean-prose prompt (no inline citations)
- tsc clean, 11 vitest pass, check-loc 0. ESLint not installed in this node_modules -> CI lints on push.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-01 07:46:37 +02:00

111 lines
3.7 KiB
TypeScript

'use client'
import { useCallback, useRef, useState } from 'react'
import type { AdvisorEvidenceMeta } from '@/lib/sdk/advisor/evidence'
import { emptyStats } from '@/lib/sdk/advisor/evidence'
export interface AdvisorTurn {
id: string
question: string
answer: string
meta: AdvisorEvidenceMeta
status: 'streaming' | 'done' | 'error'
error?: string
}
function emptyMeta(): AdvisorEvidenceMeta {
return { stats: emptyStats(), sources: [], figures: [], footnotes: [] }
}
interface UseAdvisorStreamArgs {
currentStep: string
country: string
}
/**
* Drives the Evidence Workspace: posts a question, parses the FIRST line of the response as
* structured `AdvisorEvidenceMeta`, then streams the remaining bytes as the markdown answer.
* The answer text is NEVER parsed for structure — sources/figures/footnotes come from the meta.
*/
export function useAdvisorStream({ currentStep, country }: UseAdvisorStreamArgs) {
const [turns, setTurns] = useState<AdvisorTurn[]>([])
const [isStreaming, setIsStreaming] = useState(false)
const abortRef = useRef<AbortController | null>(null)
const patch = useCallback((id: string, p: Partial<AdvisorTurn>) => {
setTurns((prev) => prev.map((t) => (t.id === id ? { ...t, ...p } : t)))
}, [])
const stop = useCallback(() => {
abortRef.current?.abort()
setIsStreaming(false)
}, [])
const send = useCallback(
async (question: string) => {
const q = question.trim()
if (!q || isStreaming) return
const id = `turn-${Date.now()}`
const history = turns.flatMap((t) => [
{ role: 'user', content: t.question },
{ role: 'assistant', content: t.answer },
])
setTurns((prev) => [...prev, { id, question: q, answer: '', meta: emptyMeta(), status: 'streaming' }])
setIsStreaming(true)
abortRef.current = new AbortController()
try {
const res = await fetch('/api/sdk/compliance-advisor/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: q, history, currentStep, country }),
signal: abortRef.current.signal,
})
if (!res.ok || !res.body) {
const e = await res.json().catch(() => ({ error: 'Unbekannter Fehler' }))
throw new Error(e.error || `Server-Fehler (${res.status})`)
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
let metaEnd = -1
let meta: AdvisorEvidenceMeta | null = null
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
if (metaEnd === -1) {
const nl = buf.indexOf('\n')
if (nl === -1) continue
metaEnd = nl + 1
try {
meta = JSON.parse(buf.slice(0, nl)) as AdvisorEvidenceMeta
} catch {
meta = null // no valid meta -> treat whole stream as answer
metaEnd = 0
}
}
patch(id, { answer: buf.slice(metaEnd), ...(meta ? { meta } : {}) })
}
buf += decoder.decode()
patch(id, { answer: buf.slice(metaEnd === -1 ? 0 : metaEnd), status: 'done', ...(meta ? { meta } : {}) })
setIsStreaming(false)
} catch (err) {
setIsStreaming(false)
if ((err as Error).name === 'AbortError') {
patch(id, { status: 'done' })
return
}
patch(id, { status: 'error', error: err instanceof Error ? err.message : 'Verbindung fehlgeschlagen' })
}
},
[isStreaming, turns, currentStep, country, patch],
)
return { turns, isStreaming, send, stop }
}