Implement persistent conversational AI chat

This commit is contained in:
2026-07-19 16:18:01 +02:00
parent fb5cae2131
commit ac611e3f7f
31 changed files with 4035 additions and 43 deletions

View File

@@ -0,0 +1,429 @@
use bds_core::i18n::UiLocale;
use bds_core::model::{ChatConversation, ChatMessage, ChatRole};
use iced::widget::text::Shaping;
use iced::widget::{
Space, button, column, container, markdown, row, scrollable, text, text_editor, text_input,
};
use iced::{Alignment, Color, Element, Length};
use crate::app::Message;
use crate::components::inputs;
use crate::i18n::{t, tw};
pub struct ChatEditorState {
pub conversation: ChatConversation,
pub messages: Vec<ChatMessage>,
rendered_messages: std::collections::HashMap<i32, Vec<markdown::Item>>,
pub input: text_editor::Content,
pub rename_input: String,
pub model_options: Vec<ChatModelChoice>,
pub streaming: bool,
pub streaming_content: String,
streaming_markdown: Vec<markdown::Item>,
pub active_tool: Option<String>,
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatModelChoice {
pub id: String,
pub label: String,
}
impl std::fmt::Display for ChatModelChoice {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.label)
}
}
impl ChatEditorState {
pub fn new(
conversation: ChatConversation,
messages: Vec<ChatMessage>,
mut model_options: Vec<ChatModelChoice>,
) -> Self {
if let Some(model) = conversation.model.as_ref()
&& !model_options.iter().any(|choice| choice.id == *model)
{
model_options.push(ChatModelChoice {
id: model.clone(),
label: model.clone(),
});
}
model_options.sort_by(|left, right| left.label.cmp(&right.label));
model_options.dedup_by(|left, right| left.id == right.id);
let rendered_messages = messages
.iter()
.filter(|message| message.role == ChatRole::Assistant)
.map(|message| {
(
message.id,
parse_safe_markdown(message.content.as_deref().unwrap_or_default()),
)
})
.collect();
Self {
rename_input: conversation.title.clone(),
conversation,
messages,
rendered_messages,
input: text_editor::Content::new(),
model_options,
streaming: false,
streaming_content: String::new(),
streaming_markdown: Vec::new(),
active_tool: None,
error: None,
}
}
pub fn set_messages(&mut self, messages: Vec<ChatMessage>) {
self.rendered_messages = messages
.iter()
.filter(|message| message.role == ChatRole::Assistant)
.map(|message| {
(
message.id,
parse_safe_markdown(message.content.as_deref().unwrap_or_default()),
)
})
.collect();
self.messages = messages;
}
pub fn set_streaming_content(&mut self, content: String) {
self.streaming_markdown = parse_safe_markdown(&content);
self.streaming_content = content;
}
pub fn clear_streaming(&mut self) {
self.streaming_content.clear();
self.streaming_markdown.clear();
}
pub fn token_totals(&self) -> (u64, u64, u64, u64) {
self.messages
.iter()
.fold((0, 0, 0, 0), |mut total, message| {
total.0 += message.token_usage_input.unwrap_or(0).max(0) as u64;
total.1 += message.token_usage_output.unwrap_or(0).max(0) as u64;
total.2 += message.cache_read_tokens.unwrap_or(0).max(0) as u64;
total.3 += message.cache_write_tokens.unwrap_or(0).max(0) as u64;
total
})
}
}
pub fn view<'a>(
state: &'a ChatEditorState,
locale: UiLocale,
ai_available: bool,
) -> Element<'a, Message> {
if !ai_available {
return container(inputs::card(
column![
text(t(locale, "chat.unavailable.title")).size(20),
text(t(locale, "chat.unavailable.guidance"))
.size(13)
.color(inputs::SECTION_COLOR),
button(text(t(locale, "chat.unavailable.openSettings")))
.on_press(Message::OpenSettingsSection(
crate::views::settings_view::SettingsSection::AI,
))
.style(inputs::primary_button),
]
.spacing(12),
))
.padding(16)
.width(Length::Fill)
.height(Length::Fill)
.into();
}
let selected_model = state.conversation.model.as_ref().and_then(|selected| {
state
.model_options
.iter()
.find(|model| model.id == *selected)
});
let model_control: Element<'a, Message> = if state.model_options.is_empty() {
text(t(locale, "chat.model.none"))
.size(12)
.color(inputs::SECTION_COLOR)
.into()
} else {
inputs::labeled_select(
&t(locale, "chat.model.label"),
&state.model_options,
selected_model,
|choice| Message::ChatModelChanged(choice.id),
)
};
let header = inputs::card(
column![
row![
text_input(&t(locale, "chat.rename.placeholder"), &state.rename_input)
.on_input(Message::ChatRenameInputChanged)
.on_submit(Message::ChatRename)
.size(18)
.padding([7, 9])
.style(inputs::field_style),
button(text(t(locale, "chat.rename.action")))
.on_press(Message::ChatRename)
.padding([8, 12])
.style(inputs::secondary_button),
button(text(t(locale, "common.delete")))
.on_press(Message::ChatDelete(state.conversation.id.clone()))
.padding([8, 12])
.style(inputs::danger_button),
]
.spacing(8)
.align_y(Alignment::Center),
model_control,
]
.spacing(10),
);
let mut message_elements: Vec<Element<'a, Message>> = Vec::new();
if state.messages.is_empty() {
message_elements.push(welcome(locale));
} else {
for message in &state.messages {
if message.role == ChatRole::Tool {
continue;
}
message_elements.push(message_view(
message,
state.rendered_messages.get(&message.id),
locale,
));
}
}
if state.streaming && !state.streaming_content.is_empty() {
message_elements.push(assistant_card(
&state.streaming_markdown,
t(locale, "chat.streaming"),
));
}
if let Some(tool) = state.active_tool.as_deref() {
message_elements.push(
inputs::card(
row![
text("").size(13),
text(tw(locale, "chat.tool.running", &[("name", tool)]))
.size(12)
.color(inputs::SECTION_COLOR),
]
.spacing(8),
)
.into(),
);
}
if let Some(error) = state.error.as_deref() {
message_elements.push(
text(error.to_string())
.size(12)
.color(Color::from_rgb8(0xE0, 0x6C, 0x75))
.into(),
);
}
let transcript = scrollable(
iced::widget::Column::with_children(message_elements)
.spacing(10)
.width(Length::Fill),
)
.anchor_bottom()
.height(Length::Fill);
let send_label = if state.streaming {
t(locale, "chat.stop")
} else {
t(locale, "chat.send")
};
let mut send_button = button(text(send_label))
.padding([8, 16])
.style(if state.streaming {
inputs::danger_button
} else {
inputs::primary_button
});
if state.streaming {
send_button = send_button.on_press(Message::ChatCancel);
} else if !state.input.text().trim().is_empty() {
send_button = send_button.on_press(Message::ChatSend);
}
let input_height =
(state.input.text().lines().count().max(1) as f32 * 22.0 + 28.0).clamp(72.0, 200.0);
let input_placeholder = t(locale, "chat.input.placeholder");
let composer = inputs::card(
column![
text_editor(&state.input)
.placeholder(input_placeholder)
.on_action(Message::ChatInputAction)
.key_binding(|key_press| {
if matches!(
key_press.key,
iced::keyboard::Key::Named(iced::keyboard::key::Named::Enter)
) && !key_press.modifiers.shift()
{
Some(iced::widget::text_editor::Binding::Custom(
Message::ChatSend,
))
} else {
iced::widget::text_editor::Binding::from_key_press(key_press)
}
})
.height(Length::Fixed(input_height))
.style(inputs::text_editor_style),
row![
text(t(locale, "chat.input.hint"))
.size(11)
.color(inputs::SECTION_COLOR),
Space::with_width(Length::Fill),
send_button,
]
.align_y(Alignment::Center),
]
.spacing(8),
);
column![header, transcript, composer]
.spacing(12)
.padding(16)
.width(Length::Fill)
.height(Length::Fill)
.into()
}
fn welcome(locale: UiLocale) -> Element<'static, Message> {
let mut items = vec![
text(t(locale, "chat.welcome.title")).size(20).into(),
text(t(locale, "chat.welcome.subtitle"))
.size(13)
.color(inputs::SECTION_COLOR)
.into(),
];
for index in 1..=5 {
items.push(
text(format!(
"{}",
t(locale, &format!("chat.welcome.tip{index}"))
))
.size(13)
.into(),
);
}
inputs::card(iced::widget::Column::with_children(items).spacing(7)).into()
}
fn message_view<'a>(
message: &'a ChatMessage,
rendered_markdown: Option<&'a Vec<markdown::Item>>,
locale: UiLocale,
) -> Element<'a, Message> {
let label = match message.role {
ChatRole::User => t(locale, "chat.role.user"),
ChatRole::Assistant => t(locale, "chat.role.assistant"),
ChatRole::System => t(locale, "chat.role.system"),
ChatRole::Tool => t(locale, "chat.role.tool"),
};
let content = message.content.as_deref().unwrap_or_default();
let body: Element<'a, Message> = if let Some(items) = rendered_markdown {
markdown::view(
items,
markdown::Settings::default(),
markdown::Style::from_palette(crate::components::inputs::app_theme().palette()),
)
.map(|url| Message::ChatLinkClicked(url.to_string()))
} else {
text(content.to_string())
.size(14)
.shaping(Shaping::Advanced)
.into()
};
let mut children: Vec<Element<'a, Message>> = vec![
text(label).size(11).color(inputs::SECTION_COLOR).into(),
body,
];
if let Some(tool_calls) = message.tool_calls.as_deref()
&& let Ok(calls) = serde_json::from_str::<Vec<serde_json::Value>>(tool_calls)
{
for call in calls {
let raw_name = call
.get("function")
.and_then(|function| function.get("name"))
.and_then(serde_json::Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| t(locale, "chat.role.tool"));
let name = raw_name.chars().take(30).collect::<String>();
let arguments = call
.get("function")
.and_then(|function| function.get("arguments"))
.and_then(serde_json::Value::as_str)
.unwrap_or_default();
let args_preview = arguments.chars().take(30).collect::<String>();
let marker = if args_preview.is_empty() {
format!("{}", tw(locale, "chat.tool.used", &[("name", &name)]))
} else {
format!(
"{} · {}",
tw(locale, "chat.tool.used", &[("name", &name)]),
args_preview
)
};
children.push(text(marker).size(11).color(inputs::SECTION_COLOR).into());
}
}
inputs::card(iced::widget::Column::with_children(children).spacing(6)).into()
}
fn assistant_card<'a>(items: &'a [markdown::Item], label: String) -> Element<'a, Message> {
let body = markdown::view(
items,
markdown::Settings::default(),
markdown::Style::from_palette(crate::components::inputs::app_theme().palette()),
)
.map(|url| Message::ChatLinkClicked(url.to_string()));
inputs::card(column![text(label).size(11).color(inputs::SECTION_COLOR), body,].spacing(6))
.into()
}
fn parse_safe_markdown(markdown_source: &str) -> Vec<markdown::Item> {
let safe = external_images_as_links(markdown_source);
markdown::parse(&safe).collect()
}
fn external_images_as_links(markdown_source: &str) -> String {
static EXTERNAL_IMAGE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
let pattern = EXTERNAL_IMAGE.get_or_init(|| {
regex::Regex::new(r"!\[([^\]]*)\]\((https?://[^)\s]+)\)")
.expect("external image Markdown regex")
});
pattern
.replace_all(markdown_source, "[🖼 $1]($2)")
.into_owned()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn markdown_never_embeds_external_images_or_raw_html() {
let rendered = parse_safe_markdown(
"# Hello\n![secret](https://example.com/a.png)<script>unsafe</script>",
);
let debug = format!("{rendered:?}");
assert!(debug.contains("Hello"));
assert!(debug.contains("secret"));
assert!(!debug.contains("script"));
assert!(debug.contains("unsafe"));
}
#[test]
fn external_images_become_safe_links_before_gfm_rendering() {
let safe = external_images_as_links("![diagram](https://example.com/a.png)");
assert_eq!(safe, "[🖼 diagram](https://example.com/a.png)");
assert_eq!(parse_safe_markdown(&safe).len(), 1);
}
}

View File

@@ -1,4 +1,5 @@
pub mod activity_bar;
pub mod chat_view;
pub mod dashboard;
pub mod git;
pub mod import_editor;

View File

@@ -5,7 +5,7 @@ use iced::widget::{Space, button, column, container, image, row, scrollable, tex
use iced::{Background, Border, Color, Element, Length, Theme};
use bds_core::i18n::UiLocale;
use bds_core::model::{ImportDefinition, Media, Post, Script, Template};
use bds_core::model::{ChatConversation, ImportDefinition, Media, Post, Script, Template};
use crate::app::Message;
use crate::components::inputs;
@@ -78,7 +78,7 @@ fn placeholder_key(view: SidebarView) -> &'static str {
SidebarView::Scripts => "sidebar.noScriptsYet",
SidebarView::Templates => "sidebar.noTemplatesYet",
SidebarView::Tags => "sidebar.tagsHeader",
SidebarView::Chat => "sidebar.chatPlaceholder",
SidebarView::Chat => "chat.sidebar.empty",
SidebarView::Import => "sidebar.importPlaceholder",
SidebarView::Git => "git.noChanges",
SidebarView::Settings => "sidebar.settingsHeader",
@@ -628,6 +628,7 @@ pub fn view(
scripts: &[Script],
templates: &[Template],
imports: &[ImportDefinition],
conversations: &[ChatConversation],
post_filter: &PostFilter,
media_filter: &MediaFilter,
media_thumbs: &std::collections::HashMap<String, Option<PathBuf>>,
@@ -655,6 +656,7 @@ pub fn view(
SidebarView::Scripts => Some(Message::CreateScript),
SidebarView::Templates => Some(Message::CreateTemplate),
SidebarView::Import => Some(Message::CreateImport),
SidebarView::Chat => Some(Message::ChatCreate),
_ => None,
};
@@ -1132,6 +1134,54 @@ pub fn view(
iced::widget::Column::with_children(items).spacing(1).into()
}
}
SidebarView::Chat => {
if conversations.is_empty() {
text(t(locale, "chat.sidebar.empty"))
.size(12)
.shaping(Shaping::Advanced)
.color(muted)
.into()
} else {
let items = conversations
.iter()
.map(|conversation| {
let style = if active_tab == Some(conversation.id.as_str()) {
item_active_style
} else {
item_style
};
let model = conversation
.model
.clone()
.unwrap_or_else(|| t(locale, "chat.model.none"));
button(
container(
column![
text(conversation.title.clone())
.size(12)
.shaping(Shaping::Advanced),
text(model).size(10).shaping(Shaping::Advanced).color(muted),
]
.spacing(1),
)
.width(Length::Fill),
)
.on_press(Message::OpenTab(Tab {
id: conversation.id.clone(),
tab_type: TabType::Chat,
title: conversation.title.clone(),
is_transient: false,
is_dirty: false,
}))
.padding([5, 8])
.width(Length::Fill)
.style(style)
.into()
})
.collect::<Vec<Element<'static, Message>>>();
iced::widget::Column::with_children(items).spacing(1).into()
}
}
SidebarView::Settings => {
// Per sidebar_views.allium SettingsNav: 9 fixed-order sections
use crate::views::settings_view::SettingsSection;
@@ -1197,11 +1247,6 @@ pub fn view(
iced::widget::Column::with_children(items).spacing(1).into()
}
SidebarView::Git => crate::views::git::sidebar_view(git_state, offline_mode, locale),
_ => text(t(locale, placeholder_key(sidebar_view)))
.size(12)
.shaping(Shaping::Advanced)
.color(muted)
.into(),
};
let content = column![header_row, Space::with_height(8.0), body,]

View File

@@ -123,6 +123,7 @@ pub fn view(
task_snapshots: &[TaskSnapshot],
theme_badge: &str,
active_post_status: Option<&str>,
chat_tokens: Option<(u64, u64, u64, u64)>,
) -> Element<'static, Message> {
let label_color = Color::from_rgb(0.60, 0.60, 0.65);
@@ -194,6 +195,28 @@ pub fn view(
"statusBar.media",
&[("count", &media_count.to_string())],
);
let chat_token_label = chat_tokens.map(|(input, output, cache_read, cache_write)| {
tw(
locale,
"statusBar.chatTokens",
&[
("input", &input.to_string()),
("output", &output.to_string()),
("cacheRead", &cache_read.to_string()),
("cacheWrite", &cache_write.to_string()),
],
)
});
let chat_tokens_el: Element<'static, Message> = chat_token_label.map_or_else(
|| Space::with_width(0).into(),
|label| {
text(label)
.size(11)
.shaping(Shaping::Advanced)
.color(label_color)
.into()
},
);
// Airplane mode toggle — ✈ icon
let airplane_btn = button(text("\u{2708}").size(13).shaping(Shaping::Advanced))
@@ -225,6 +248,7 @@ pub fn view(
.size(11)
.shaping(Shaping::Advanced)
.color(label_color),
chat_tokens_el,
text(theme_badge.to_string())
.size(11)
.shaping(Shaping::Advanced)

View File

@@ -7,7 +7,7 @@ use iced::{Alignment, Background, Color, Element, Length, Padding, Theme};
use bds_core::engine::git::GitCommit;
use bds_core::i18n::UiLocale;
use bds_core::model::{ImportDefinition, Media, Post, Project, Script, Template};
use bds_core::model::{ChatConversation, ImportDefinition, Media, Post, Project, Script, Template};
use crate::app::Message;
use crate::state::navigation::{OutputEntry, PanelTab, SidebarView, TaskSnapshot};
@@ -16,6 +16,7 @@ use crate::state::tabs::{Tab, TabType};
use crate::state::toast::Toast;
use crate::views::{
activity_bar,
chat_view::{self, ChatEditorState},
dashboard::DashboardState,
git::{self, GitDiffState, GitUiState},
media_editor::{self, MediaEditorState},
@@ -88,6 +89,7 @@ pub fn view<'a>(
sidebar_scripts: &'a [Script],
sidebar_templates: &'a [Template],
sidebar_imports: &'a [ImportDefinition],
chat_conversations: &'a [ChatConversation],
// Sidebar filters
post_filter: &'a PostFilter,
media_filter: &'a MediaFilter,
@@ -121,6 +123,7 @@ pub fn view<'a>(
template_editors: &'a HashMap<String, TemplateEditorState>,
script_editors: &'a HashMap<String, ScriptEditorState>,
import_editors: &'a HashMap<String, crate::views::import_editor::ImportEditorState>,
chat_editors: &'a HashMap<String, ChatEditorState>,
tags_view_state: Option<&'a TagsViewState>,
settings_state: Option<&'a SettingsViewState>,
dashboard_state: Option<&'a DashboardState>,
@@ -150,6 +153,7 @@ pub fn view<'a>(
template_editors,
script_editors,
import_editors,
chat_editors,
tags_view_state,
settings_state,
dashboard_state,
@@ -204,6 +208,7 @@ pub fn view<'a>(
sidebar_scripts,
sidebar_templates,
sidebar_imports,
chat_conversations,
post_filter,
media_filter,
sidebar_media_thumbs,
@@ -262,6 +267,9 @@ pub fn view<'a>(
task_snapshots,
theme_badge,
active_post_status.as_deref(),
active_tab
.and_then(|id| chat_editors.get(id))
.map(ChatEditorState::token_totals),
);
let base_layout: Element<'a, Message> = column![main_row, separator_h(), status]
@@ -387,6 +395,7 @@ fn route_content_area<'a>(
template_editors: &'a HashMap<String, TemplateEditorState>,
script_editors: &'a HashMap<String, ScriptEditorState>,
import_editors: &'a HashMap<String, crate::views::import_editor::ImportEditorState>,
chat_editors: &'a HashMap<String, ChatEditorState>,
tags_view_state: Option<&'a TagsViewState>,
settings_state: Option<&'a SettingsViewState>,
dashboard_state: Option<&'a DashboardState>,
@@ -458,6 +467,13 @@ fn route_content_area<'a>(
loading_view(locale)
}
}
ContentRoute::Chat(tab_id) => {
if let Some(state) = chat_editors.get(tab_id) {
chat_view::view(state, locale, is_ai_enabled(settings_state, offline_mode))
} else {
loading_view(locale)
}
}
ContentRoute::Tags => {
if let Some(state) = tags_view_state {
tags_view::view(state, locale)
@@ -504,6 +520,7 @@ enum ContentRoute<'a> {
Templates(&'a str),
Scripts(&'a str),
Import(&'a str),
Chat(&'a str),
Tags,
Settings,
SiteValidation,
@@ -577,6 +594,7 @@ fn route_kind<'a>(
ContentRoute::Loading
}
}
TabType::Chat => ContentRoute::Chat(tab_id),
TabType::Tags => {
if tags_view_state.is_some() {
ContentRoute::Tags
@@ -595,7 +613,6 @@ fn route_kind<'a>(
TabType::MetadataDiff => ContentRoute::MetadataDiff,
TabType::GitDiff => ContentRoute::GitDiff(tab_id),
TabType::Style
| TabType::Chat
| TabType::MenuEditor
| TabType::Documentation
| TabType::ApiDocumentation
@@ -658,7 +675,6 @@ mod tests {
let site_validation_state = SiteValidationState::default();
let unsupported = [
TabType::Style,
TabType::Chat,
TabType::MenuEditor,
TabType::Documentation,
TabType::ApiDocumentation,
@@ -712,6 +728,31 @@ mod tests {
assert!(matches!(route, ContentRoute::GitDiff("git-diff:file.txt")));
}
#[test]
fn chat_tab_routes_to_real_chat_view() {
let empty_posts = HashMap::new();
let empty_media = HashMap::new();
let empty_templates = HashMap::new();
let empty_scripts = HashMap::new();
let empty_imports = HashMap::new();
let site_validation_state = SiteValidationState::default();
let tabs = vec![tab("conversation", TabType::Chat, "Chat")];
let route = route_kind(
&tabs,
Some("conversation"),
&empty_posts,
&empty_media,
&empty_templates,
&empty_scripts,
&empty_imports,
None,
None,
None,
&site_validation_state,
);
assert!(matches!(route, ContentRoute::Chat("conversation")));
}
#[test]
fn validation_tabs_route_to_real_views() {
let empty_posts = HashMap::new();