diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index b087fd9..52e3723 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -176,8 +176,9 @@ jobs: echo "Changed files:" echo "$CHANGED" - # Agent: core libs, agent code, agent Dockerfile - if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|Dockerfile\.agent|Cargo\.(toml|lock))'; then + # Agent: core libs, agent code, agent Dockerfile, and the docs and + # README the help assistant answers from (baked into the image) + if echo "$CHANGED" | grep -qE '^(compliance-core/|compliance-agent/|compliance-graph/|compliance-dast/|Dockerfile\.agent|Cargo\.(toml|lock)|docs/|README\.md)'; then echo "agent=true" >> "$GITHUB_OUTPUT" else echo "agent=false" >> "$GITHUB_OUTPUT" diff --git a/Cargo.lock b/Cargo.lock index 98deeff..1d84c9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -762,6 +762,7 @@ dependencies = [ "hex", "js-sys", "mongodb", + "pulldown-cmark", "rand 0.9.2", "reqwest", "secrecy", @@ -4367,6 +4368,24 @@ dependencies = [ "psl-types", ] +[[package]] +name = "pulldown-cmark" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +dependencies = [ + "bitflags", + "memchr", + "pulldown-cmark-escape", + "unicase", +] + +[[package]] +name = "pulldown-cmark-escape" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" + [[package]] name = "quinn" version = "0.11.9" diff --git a/compliance-agent/src/api/handlers/help_chat.rs b/compliance-agent/src/api/handlers/help_chat.rs index dfbc4ec..ed0b1e2 100644 --- a/compliance-agent/src/api/handlers/help_chat.rs +++ b/compliance-agent/src/api/handlers/help_chat.rs @@ -171,21 +171,23 @@ pub async fn help_chat( let context = doc_context(); let system_prompt = if context.is_empty() { - "You are a helpful assistant for the Compliance Scanner project. \ - Answer questions about how to use and configure it. \ - No documentation was loaded at startup, so rely on your general knowledge." + "You are the help assistant of Prüfwerk, BreakPilot's security and CRA \ + compliance scanner. Answer questions about how to use it, in the language \ + the question is asked in. No documentation was loaded, so say when you are \ + unsure rather than guessing." .to_string() } else { format!( - "You are a helpful assistant for the Compliance Scanner project. \ - Answer questions about how to use, configure, and understand it \ - using the documentation below as your primary source of truth.\n\n\ + "You are the help assistant of Prüfwerk, BreakPilot's security and CRA \ + compliance scanner. Answer questions about how to use, configure, and \ + understand it using the documentation below as your source of truth.\n\n\ Rules:\n\ - - Prefer information from the provided docs over general knowledge\n\ - - Quote or reference the relevant doc section when it helps\n\ - - If the docs do not cover the topic, say so clearly\n\ - - Be concise — lead with the answer, then explain if needed\n\ - - Use markdown formatting for readability\n\n\ + - Answer in the language the question is asked in (usually German)\n\ + - Lead with a direct answer (yes/no when the question allows), then the details\n\ + - Prefer the docs over general knowledge; if they do not cover it, say so\n\ + - Name the documentation page by its title, never by its file path\n\ + - Keep it short: a few sentences or a short list, for a narrow chat panel\n\ + - Use markdown (bold, lists, inline code); no tables, no HTML\n\n\ ## Project Documentation\n\n{context}" ) }; diff --git a/compliance-dashboard/Cargo.toml b/compliance-dashboard/Cargo.toml index 5809113..a97f107 100644 --- a/compliance-dashboard/Cargo.toml +++ b/compliance-dashboard/Cargo.toml @@ -51,6 +51,8 @@ chrono = { workspace = true } tracing = { workspace = true } dioxus-logger = "0.6" thiserror = { workspace = true } +# Renders the help assistant's markdown answers; no raw HTML passes through. +pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] } # Web-only reqwest = { workspace = true, optional = true } diff --git a/compliance-dashboard/assets/main.css b/compliance-dashboard/assets/main.css index 39295a8..3550b69 100644 --- a/compliance-dashboard/assets/main.css +++ b/compliance-dashboard/assets/main.css @@ -3791,6 +3791,9 @@ tbody tr:last-child td { font-size: 13px; gap: 8px; } +@media (max-width: 480px) { + .help-chat-panel { right: 16px; left: 16px; width: auto; bottom: 16px; height: 70vh; } +} .help-chat-hint { font-size: 12px; color: var(--text-tertiary); @@ -3829,14 +3832,102 @@ tbody tr:last-child td { border: 1px solid var(--border); border-bottom-left-radius: 4px; } -.help-msg-assistant .help-msg-content code { +/* Markdown answers: compact prose that fits the narrow panel. */ +.help-md > :first-child { margin-top: 0; } +.help-md > :last-child { margin-bottom: 0; } +.help-md p, +.help-md ul, +.help-md ol, +.help-md pre, +.help-md table { margin: 0 0 8px; } +.help-md ul, +.help-md ol { padding-left: 18px; } +.help-md li { margin: 2px 0; } +.help-md li::marker { color: var(--accent); } +.help-md h1, +.help-md h2, +.help-md h3, +.help-md h4 { + font-family: var(--font-display); + font-size: 13px; + font-weight: 600; + margin: 10px 0 4px; +} +.help-md strong { font-weight: 600; } +.help-md a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; } +.help-md code { background: var(--accent-muted); padding: 1px 5px; - border-radius: 3px; + border-radius: 4px; font-family: var(--font-mono); font-size: 12px; + word-break: break-word; +} +.help-md pre { + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 8px; + padding: 8px 10px; + overflow-x: auto; +} +.help-md pre code { background: none; padding: 0; } +.help-md blockquote { + margin: 0 0 8px; + padding-left: 10px; + border-left: 3px solid var(--border-bright); + color: var(--text-secondary); +} +.help-md table { border-collapse: collapse; font-size: 12px; display: block; overflow-x: auto; } +.help-md th, +.help-md td { border: 1px solid var(--border); padding: 3px 6px; text-align: left; } +.help-msg-error { + color: var(--danger); + border-color: color-mix(in oklch, var(--danger) 40%, var(--border)) !important; +} +.help-chat-mark { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + border-radius: 8px; + background: var(--accent-muted); + color: var(--accent); +} +.help-chat-suggestions { + display: flex; + flex-direction: column; + gap: 6px; + width: 100%; + margin-top: 6px; +} +.help-chat-suggestion { + text-align: left; + background: var(--bg-elevated); + border: 1px solid var(--border); + border-radius: 10px; + padding: 8px 12px; + font: inherit; + font-size: 13px; + color: var(--text-primary); + cursor: pointer; + transition: border-color 0.15s, background 0.15s; +} +.help-chat-suggestion:hover { + border-color: var(--accent); + background: var(--accent-muted); +} +.help-chat-disclaimer { + margin: 0; + padding: 0 14px 10px; + background: var(--bg-primary); + font-size: 11px; + color: var(--text-tertiary); } .help-msg-loading { + display: flex; + align-items: center; + gap: 8px; padding: 10px 14px; border-radius: 12px; background: var(--bg-elevated); diff --git a/compliance-dashboard/src/components/help_chat.rs b/compliance-dashboard/src/components/help_chat.rs index df6bd01..b24a64c 100644 --- a/compliance-dashboard/src/components/help_chat.rs +++ b/compliance-dashboard/src/components/help_chat.rs @@ -1,198 +1,188 @@ +//! The help assistant: a floating panel that answers questions about Prüfwerk +//! from its documentation. + use dioxus::prelude::*; use dioxus_free_icons::icons::bs_icons::*; use dioxus_free_icons::Icon; +use crate::components::markdown::render_markdown; +use crate::i18n::texts::help; +use crate::i18n::use_lang; use crate::infrastructure::help_chat::{send_help_chat_message, HelpChatHistoryMessage}; -// ── Message model ──────────────────────────────────────────────────────────── - -#[derive(Clone, Debug)] -struct ChatMsg { - role: String, - content: String, +/// Who wrote a message in the conversation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Role { + User, + Assistant, + /// A failed request, shown in the conversation but never sent back as + /// history. + Error, } -// ── Component ──────────────────────────────────────────────────────────────── +/// One message of the conversation. An assistant message keeps its rendered +/// HTML, so the markdown is parsed once rather than on every render. +#[derive(Clone, Debug, PartialEq)] +struct ChatMsg { + role: Role, + content: String, + html: String, +} +/// Floating help button and the conversation panel it opens. #[component] pub fn HelpChat() -> Element { + let lang = use_lang()(); let mut is_open = use_signal(|| false); let mut messages = use_signal(Vec::::new); let mut input_text = use_signal(String::new); let mut is_loading = use_signal(|| false); - // Send message handler - let on_send = move |_| { - let text = input_text().trim().to_string(); + // Send `text` with the conversation so far. The one path for the button, + // Enter, and the suggested questions. + let mut send = move |text: String| { + let text = text.trim().to_string(); if text.is_empty() || is_loading() { return; } - - // Push user message + let history: Vec = messages + .read() + .iter() + .filter_map(|m| { + let role = match m.role { + Role::User => "user", + Role::Assistant => "assistant", + Role::Error => return None, + }; + Some(HelpChatHistoryMessage { + role: role.to_string(), + content: m.content.clone(), + }) + }) + .collect(); messages.write().push(ChatMsg { - role: "user".into(), + role: Role::User, content: text.clone(), + html: String::new(), }); input_text.set(String::new()); is_loading.set(true); - - // Build history for API call (exclude last user message, it goes as `message`) - let history: Vec = messages() - .iter() - .rev() - .skip(1) // skip the user message we just added - .rev() - .map(|m| HelpChatHistoryMessage { - role: m.role.clone(), - content: m.content.clone(), - }) - .collect(); - spawn(async move { - match send_help_chat_message(text, history).await { - Ok(resp) => { - messages.write().push(ChatMsg { - role: "assistant".into(), - content: resp.data.message, - }); - } - Err(e) => { - messages.write().push(ChatMsg { - role: "assistant".into(), - content: format!("Error: {e}"), - }); - } - } + let reply = match send_help_chat_message(text, history).await { + Ok(resp) => ChatMsg { + role: Role::Assistant, + html: render_markdown(&resp.data.message), + content: resp.data.message, + }, + Err(e) => ChatMsg { + role: Role::Error, + content: format!("{}: {e}", help::FAILED.get(lang)), + html: String::new(), + }, + }; + messages.write().push(reply); is_loading.set(false); }); }; - // Key handler for Enter to send - let on_keydown = move |e: KeyboardEvent| { - if e.key() == Key::Enter && !e.modifiers().shift() { - e.prevent_default(); - let text = input_text().trim().to_string(); - if text.is_empty() || is_loading() { - return; - } - messages.write().push(ChatMsg { - role: "user".into(), - content: text.clone(), - }); - input_text.set(String::new()); - is_loading.set(true); - - let history: Vec = messages() - .iter() - .rev() - .skip(1) - .rev() - .map(|m| HelpChatHistoryMessage { - role: m.role.clone(), - content: m.content.clone(), - }) - .collect(); - - spawn(async move { - match send_help_chat_message(text, history).await { - Ok(resp) => { - messages.write().push(ChatMsg { - role: "assistant".into(), - content: resp.data.message, - }); - } - Err(e) => { - messages.write().push(ChatMsg { - role: "assistant".into(), - content: format!("Error: {e}"), - }); - } - } - is_loading.set(false); - }); - } - }; - - rsx! { - // Floating toggle button - if !is_open() { + if !is_open() { + return rsx! { button { class: "help-chat-toggle", onclick: move |_| is_open.set(true), - title: "Help", - Icon { icon: BsQuestionCircle, width: 22, height: 22 } + title: help::OPEN.get(lang), + "aria-label": help::OPEN.get(lang), + Icon { icon: BsQuestionLg, width: 22, height: 22 } } - } + }; + } - // Chat panel - if is_open() { - div { class: "help-chat-panel", - // Header - div { class: "help-chat-header", - span { class: "help-chat-title", - Icon { icon: BsRobot, width: 16, height: 16 } - "Help Assistant" - } - button { - class: "help-chat-close", - onclick: move |_| is_open.set(false), - Icon { icon: BsX, width: 18, height: 18 } - } + rsx! { + div { class: "help-chat-panel", role: "dialog", "aria-label": help::TITLE.get(lang), + div { class: "help-chat-header", + span { class: "help-chat-title", + span { class: "help-chat-mark", Icon { icon: BsStars, width: 14, height: 14 } } + {help::TITLE.get(lang)} } + button { + class: "help-chat-close", + title: help::CLOSE.get(lang), + "aria-label": help::CLOSE.get(lang), + onclick: move |_| is_open.set(false), + Icon { icon: BsX, width: 18, height: 18 } + } + } - // Messages area - div { class: "help-chat-messages", - if messages().is_empty() { - div { class: "help-chat-empty", - p { "Ask me anything about Prüfwerk." } - p { class: "help-chat-hint", - "e.g. \"How do I add a repository?\" or \"What is SBOM?\"" - } - } - } - for (i, msg) in messages().iter().enumerate() { - div { - key: "{i}", - class: if msg.role == "user" { "help-msg help-msg-user" } else { "help-msg help-msg-assistant" }, - div { class: "help-msg-content", - dangerous_inner_html: if msg.role == "assistant" { - // Basic markdown rendering: bold, code, newlines - msg.content - .replace("**", "") - .replace("\n\n", "

") - .replace("\n- ", "
- ") - .replace("`", "") - } else { - msg.content.clone() + div { class: "help-chat-messages", "aria-live": "polite", + if messages.read().is_empty() { + div { class: "help-chat-empty", + p { {help::INTRO.get(lang)} } + div { class: "help-chat-suggestions", + for suggestion in help::SUGGESTIONS { + button { + class: "help-chat-suggestion", + onclick: move |_| send(suggestion.get(lang).to_string()), + {suggestion.get(lang)} } } } } - if is_loading() { - div { class: "help-msg help-msg-assistant", - div { class: "help-msg-loading", "Thinking..." } + } + for (i, msg) in messages.read().iter().enumerate() { + match msg.role { + Role::User => rsx! { + div { key: "{i}", class: "help-msg help-msg-user", + div { class: "help-msg-content", "{msg.content}" } + } + }, + // Rendered by `render_markdown`, which escapes raw + // HTML and neutralises unsafe links. + Role::Assistant => rsx! { + div { key: "{i}", class: "help-msg help-msg-assistant", + div { class: "help-msg-content help-md", dangerous_inner_html: "{msg.html}" } + } + }, + Role::Error => rsx! { + div { key: "{i}", class: "help-msg help-msg-assistant", + div { class: "help-msg-content help-msg-error", "{msg.content}" } + } + }, + } + } + if is_loading() { + div { class: "help-msg help-msg-assistant", + div { class: "help-msg-loading", + span { class: "spinner" } + {help::THINKING.get(lang)} } } } + } - // Input area - div { class: "help-chat-input", - input { - r#type: "text", - placeholder: "Ask a question...", - value: "{input_text}", - disabled: is_loading(), - oninput: move |e| input_text.set(e.value()), - onkeydown: on_keydown, - } - button { - class: "help-chat-send", - disabled: is_loading() || input_text().trim().is_empty(), - onclick: on_send, - Icon { icon: BsSend, width: 14, height: 14 } - } + div { class: "help-chat-input", + input { + r#type: "text", + placeholder: help::PLACEHOLDER.get(lang), + value: "{input_text}", + disabled: is_loading(), + oninput: move |e| input_text.set(e.value()), + onkeydown: move |e: KeyboardEvent| { + if e.key() == Key::Enter && !e.modifiers().shift() { + e.prevent_default(); + send(input_text()); + } + }, + } + button { + class: "help-chat-send", + title: help::SEND.get(lang), + "aria-label": help::SEND.get(lang), + disabled: is_loading() || input_text().trim().is_empty(), + onclick: move |_| send(input_text()), + Icon { icon: BsSend, width: 14, height: 14 } } } + p { class: "help-chat-disclaimer", {help::DISCLAIMER.get(lang)} } } } } diff --git a/compliance-dashboard/src/components/markdown.rs b/compliance-dashboard/src/components/markdown.rs new file mode 100644 index 0000000..8a64e12 --- /dev/null +++ b/compliance-dashboard/src/components/markdown.rs @@ -0,0 +1,108 @@ +//! Markdown from the language model, made safe to show as HTML. +//! +//! The help assistant answers in markdown. It is model output, so nothing in +//! it may reach the page as markup of its own: raw HTML is shown as text, and +//! links keep only web and mail targets. + +use pulldown_cmark::{CowStr, Event, Options, Parser, Tag}; + +/// Link targets kept as they are; anything else (`javascript:`, `data:`, …) +/// becomes an inert `#`. +const SAFE_SCHEMES: &[&str] = &["https://", "http://", "mailto:"]; + +/// Render `markdown` to HTML that is safe to insert into the page. +/// +/// # Arguments +/// +/// * `markdown` - Text in CommonMark (with tables and strikethrough) +/// +/// # Returns +/// +/// HTML with every raw HTML tag escaped and every link pointing at a web +/// address, a mail address, a relative path, or `#`. +/// +/// # Examples +/// +/// ```ignore +/// assert_eq!(render_markdown("**a** `b`"), "

a b

\n"); +/// ``` +pub fn render_markdown(markdown: &str) -> String { + let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH; + let events = Parser::new_ext(markdown, options).map(|event| match event { + // Shown as the text it is; `push_html` escapes text. + Event::Html(html) | Event::InlineHtml(html) => Event::Text(html), + Event::Start(Tag::Link { + link_type, + dest_url, + title, + id, + }) => Event::Start(Tag::Link { + link_type, + dest_url: safe_url(dest_url), + title, + id, + }), + Event::Start(Tag::Image { + link_type, + dest_url, + title, + id, + }) => Event::Start(Tag::Image { + link_type, + dest_url: safe_url(dest_url), + title, + id, + }), + other => other, + }); + let mut html = String::with_capacity(markdown.len() * 3 / 2); + pulldown_cmark::html::push_html(&mut html, events); + html +} + +/// `url` when it is a web or mail address or a relative path, else `#`. +fn safe_url(url: CowStr<'_>) -> CowStr<'_> { + let lower = url.trim().to_ascii_lowercase(); + let relative = !lower.contains(':'); + if relative || SAFE_SCHEMES.iter().any(|scheme| lower.starts_with(scheme)) { + url + } else { + CowStr::Borrowed("#") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bold_and_code_are_closed() { + let html = render_markdown("**HTTPS only** and `ssh://` are rejected"); + assert_eq!( + html, + "

HTTPS only and ssh:// are rejected

\n" + ); + } + + #[test] + fn lists_render_as_lists() { + let html = render_markdown("- one\n- two"); + assert!(html.contains("
    ") && html.contains("
  • two
  • ")); + } + + #[test] + fn raw_html_is_shown_as_text() { + let html = render_markdown(" hi"); + assert!(!html.contains("