Implement persistent conversational AI chat
This commit is contained in:
@@ -11,6 +11,7 @@ iced = { workspace = true }
|
||||
muda = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
open = { workspace = true }
|
||||
|
||||
@@ -13,8 +13,9 @@ use bds_core::engine::ai::{self, AiEndpointConfig, AiEndpointKind};
|
||||
use bds_core::engine::task::{TaskId, TaskManager, TaskStatus};
|
||||
use bds_core::i18n::{UiLocale, detect_os_locale, normalize_language};
|
||||
use bds_core::model::{
|
||||
DomainEntity, DomainEvent, ImportDefinition, ImportReport, Media, NotificationAction, Post,
|
||||
PostStatus, PostTranslation, Project, PublishingPreferences, Script, SshMode, Template,
|
||||
ChatConversation, DomainEntity, DomainEvent, ImportDefinition, ImportReport, Media,
|
||||
NotificationAction, Post, PostStatus, PostTranslation, Project, PublishingPreferences, Script,
|
||||
SshMode, Template,
|
||||
};
|
||||
|
||||
use crate::components::webview::{self, WebViewConfig, WebViewController};
|
||||
@@ -27,6 +28,7 @@ use crate::state::sidebar_filter::{CalendarMonth, CalendarYear, MediaFilter, Pos
|
||||
use crate::state::tabs::{self, Tab, TabType};
|
||||
use crate::state::toast::{Toast, ToastLevel};
|
||||
use crate::views::{
|
||||
chat_view::{ChatEditorState, ChatModelChoice},
|
||||
dashboard::{
|
||||
DashboardCategory, DashboardRecentPost, DashboardState, DashboardStats, DashboardTag,
|
||||
DashboardTimelineMonth,
|
||||
@@ -322,6 +324,21 @@ pub enum Message {
|
||||
CreateTemplate,
|
||||
CreateImport,
|
||||
|
||||
// Conversational AI
|
||||
ChatCreate,
|
||||
ChatRenameInputChanged(String),
|
||||
ChatRename,
|
||||
ChatDelete(String),
|
||||
ChatModelChanged(String),
|
||||
ChatInputAction(iced::widget::text_editor::Action),
|
||||
ChatSend,
|
||||
ChatCancel,
|
||||
ChatLinkClicked(String),
|
||||
ChatFinished {
|
||||
conversation_id: String,
|
||||
result: Result<engine::chat::ChatTurnResult, String>,
|
||||
},
|
||||
|
||||
Noop,
|
||||
InitMenuBar,
|
||||
}
|
||||
@@ -812,6 +829,7 @@ pub struct BdsApp {
|
||||
sidebar_scripts: Vec<Script>,
|
||||
sidebar_templates: Vec<Template>,
|
||||
sidebar_imports: Vec<ImportDefinition>,
|
||||
chat_conversations: Vec<ChatConversation>,
|
||||
sidebar_media_thumbs: HashMap<String, Option<std::path::PathBuf>>,
|
||||
sidebar_posts_has_more: bool,
|
||||
sidebar_media_has_more: bool,
|
||||
@@ -838,6 +856,7 @@ pub struct BdsApp {
|
||||
// Tasks
|
||||
task_manager: Arc<TaskManager>,
|
||||
domain_events: engine::domain_events::EventSubscription,
|
||||
chat_events: std::sync::mpsc::Receiver<engine::chat::ChatEvent>,
|
||||
script_menu_actions: Arc<Mutex<Vec<MenuAction>>>,
|
||||
task_snapshots: Vec<TaskSnapshot>,
|
||||
collapsed_task_groups: HashSet<String>,
|
||||
@@ -883,6 +902,7 @@ pub struct BdsApp {
|
||||
template_editors: HashMap<String, TemplateEditorState>,
|
||||
script_editors: HashMap<String, ScriptEditorState>,
|
||||
import_editors: HashMap<String, ImportEditorState>,
|
||||
chat_editors: HashMap<String, ChatEditorState>,
|
||||
tags_view_state: Option<TagsViewState>,
|
||||
settings_state: Option<SettingsViewState>,
|
||||
dashboard_state: Option<DashboardState>,
|
||||
@@ -980,6 +1000,10 @@ impl BdsApp {
|
||||
registry.set_enabled(MenuAction::Find, false);
|
||||
registry.set_enabled(MenuAction::Replace, false);
|
||||
registry.set_enabled(MenuAction::OpenInBrowser, false);
|
||||
let chat_conversations = db
|
||||
.as_ref()
|
||||
.and_then(|db| engine::chat::list_conversations(db.conn()).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
(
|
||||
Self {
|
||||
@@ -995,6 +1019,7 @@ impl BdsApp {
|
||||
sidebar_scripts: Vec::new(),
|
||||
sidebar_templates: Vec::new(),
|
||||
sidebar_imports: Vec::new(),
|
||||
chat_conversations,
|
||||
sidebar_media_thumbs: HashMap::new(),
|
||||
sidebar_posts_has_more: false,
|
||||
sidebar_media_has_more: false,
|
||||
@@ -1011,6 +1036,7 @@ impl BdsApp {
|
||||
panel_tab: PanelTab::Tasks,
|
||||
task_manager: Arc::new(TaskManager::default()),
|
||||
domain_events: engine::domain_events::subscribe(),
|
||||
chat_events: engine::chat::subscribe_events(),
|
||||
script_menu_actions: Arc::new(Mutex::new(Vec::new())),
|
||||
task_snapshots: Vec::new(),
|
||||
collapsed_task_groups: HashSet::new(),
|
||||
@@ -1040,6 +1066,7 @@ impl BdsApp {
|
||||
template_editors: HashMap::new(),
|
||||
script_editors: HashMap::new(),
|
||||
import_editors: HashMap::new(),
|
||||
chat_editors: HashMap::new(),
|
||||
tags_view_state: None,
|
||||
settings_state: None,
|
||||
dashboard_state: None,
|
||||
@@ -1057,6 +1084,7 @@ impl BdsApp {
|
||||
|
||||
#[cfg(test)]
|
||||
fn new_for_tests(db: Database, project: Project, data_dir: PathBuf) -> Self {
|
||||
let chat_conversations = engine::chat::list_conversations(db.conn()).unwrap_or_default();
|
||||
Self {
|
||||
db: Some(db),
|
||||
db_path: data_dir.join("bds.db"),
|
||||
@@ -1070,6 +1098,7 @@ impl BdsApp {
|
||||
sidebar_scripts: Vec::new(),
|
||||
sidebar_templates: Vec::new(),
|
||||
sidebar_imports: Vec::new(),
|
||||
chat_conversations,
|
||||
sidebar_media_thumbs: HashMap::new(),
|
||||
sidebar_posts_has_more: false,
|
||||
sidebar_media_has_more: false,
|
||||
@@ -1086,6 +1115,7 @@ impl BdsApp {
|
||||
panel_tab: PanelTab::Tasks,
|
||||
task_manager: Arc::new(TaskManager::default()),
|
||||
domain_events: engine::domain_events::subscribe(),
|
||||
chat_events: engine::chat::subscribe_events(),
|
||||
script_menu_actions: Arc::new(Mutex::new(Vec::new())),
|
||||
task_snapshots: Vec::new(),
|
||||
collapsed_task_groups: HashSet::new(),
|
||||
@@ -1114,6 +1144,7 @@ impl BdsApp {
|
||||
template_editors: HashMap::new(),
|
||||
script_editors: HashMap::new(),
|
||||
import_editors: HashMap::new(),
|
||||
chat_editors: HashMap::new(),
|
||||
tags_view_state: None,
|
||||
settings_state: None,
|
||||
dashboard_state: None,
|
||||
@@ -1151,6 +1182,9 @@ impl BdsApp {
|
||||
self.refresh_sidebar_posts()
|
||||
} else if new_view == SidebarView::Git && new_visible {
|
||||
self.refresh_git()
|
||||
} else if new_view == SidebarView::Chat && new_visible {
|
||||
self.refresh_chat_conversations();
|
||||
Task::none()
|
||||
} else {
|
||||
Task::none()
|
||||
}
|
||||
@@ -1172,6 +1206,144 @@ impl BdsApp {
|
||||
Message::CreateScript => self.create_sidebar_script(),
|
||||
Message::CreateTemplate => self.create_sidebar_template(),
|
||||
Message::CreateImport => self.create_sidebar_import(),
|
||||
Message::ChatCreate => self.create_chat_conversation(),
|
||||
Message::ChatRenameInputChanged(value) => {
|
||||
if let Some(state) = self.active_chat_state_mut() {
|
||||
state.rename_input = value;
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatRename => {
|
||||
let Some(id) = self.active_chat_id().map(str::to_string) else {
|
||||
return Task::none();
|
||||
};
|
||||
let Some(title) = self
|
||||
.chat_editors
|
||||
.get(&id)
|
||||
.map(|state| state.rename_input.clone())
|
||||
else {
|
||||
return Task::none();
|
||||
};
|
||||
let result = self
|
||||
.db
|
||||
.as_ref()
|
||||
.ok_or_else(|| "database unavailable".to_string())
|
||||
.and_then(|db| {
|
||||
engine::chat::rename_conversation(db.conn(), &id, &title)
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match result {
|
||||
Ok(conversation) => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&id) {
|
||||
state.conversation = conversation.clone();
|
||||
state.rename_input = conversation.title.clone();
|
||||
}
|
||||
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) {
|
||||
tab.title = conversation.title.clone();
|
||||
}
|
||||
self.refresh_chat_conversations();
|
||||
}
|
||||
Err(error) => self.notify(ToastLevel::Error, &error),
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatDelete(id) => {
|
||||
let result = self
|
||||
.db
|
||||
.as_ref()
|
||||
.ok_or_else(|| "database unavailable".to_string())
|
||||
.and_then(|db| {
|
||||
engine::chat::delete_conversation(db.conn(), &id)
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.chat_editors.remove(&id);
|
||||
if let Some(next) = tabs::close_tab(&mut self.tabs, &id) {
|
||||
self.active_tab = self.tabs.get(next).map(|tab| tab.id.clone());
|
||||
} else {
|
||||
self.active_tab = None;
|
||||
}
|
||||
self.refresh_chat_conversations();
|
||||
self.notify(ToastLevel::Success, &t(self.ui_locale, "chat.deleted"));
|
||||
}
|
||||
Err(error) => self.notify(ToastLevel::Error, &error),
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatModelChanged(model) => {
|
||||
let Some(id) = self.active_chat_id().map(str::to_string) else {
|
||||
return Task::none();
|
||||
};
|
||||
let result = self
|
||||
.db
|
||||
.as_ref()
|
||||
.ok_or_else(|| "database unavailable".to_string())
|
||||
.and_then(|db| {
|
||||
engine::chat::set_conversation_model(db.conn(), &id, &model)
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match result {
|
||||
Ok(()) => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&id) {
|
||||
state.conversation.model = Some(model);
|
||||
}
|
||||
self.refresh_chat_conversations();
|
||||
}
|
||||
Err(error) => self.notify(ToastLevel::Error, &error),
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatInputAction(action) => {
|
||||
if let Some(state) = self.active_chat_state_mut() {
|
||||
state.input.perform(action);
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatSend => self.send_active_chat_message(),
|
||||
Message::ChatCancel => {
|
||||
if let Some(id) = self.active_chat_id() {
|
||||
engine::chat::cancel_chat(id);
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatLinkClicked(url) => {
|
||||
if url.starts_with("https://") || url.starts_with("http://") {
|
||||
if let Err(error) = open::that_detached(&url) {
|
||||
self.notify(ToastLevel::Error, &error.to_string());
|
||||
}
|
||||
} else {
|
||||
self.notify(ToastLevel::Error, &t(self.ui_locale, "chat.link.refused"));
|
||||
}
|
||||
Task::none()
|
||||
}
|
||||
Message::ChatFinished {
|
||||
conversation_id,
|
||||
result,
|
||||
} => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&conversation_id) {
|
||||
state.streaming = false;
|
||||
state.clear_streaming();
|
||||
state.active_tool = None;
|
||||
match result {
|
||||
Ok(_) => state.error = None,
|
||||
Err(error) => state.error = Some(error),
|
||||
}
|
||||
if let Some(db) = &self.db {
|
||||
state.set_messages(
|
||||
engine::chat::list_messages(db.conn(), &conversation_id)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
if let Ok(conversation) =
|
||||
engine::chat::get_conversation(db.conn(), &conversation_id)
|
||||
{
|
||||
state.conversation = conversation;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.refresh_chat_conversations();
|
||||
self.refresh_counts()
|
||||
}
|
||||
Message::OpenSettingsSection(section) => {
|
||||
self.sidebar_view = SidebarView::Settings;
|
||||
self.sidebar_visible = true;
|
||||
@@ -1838,6 +2010,7 @@ impl BdsApp {
|
||||
Message::TaskTick => {
|
||||
self.task_manager.evict_expired();
|
||||
self.refresh_task_snapshots();
|
||||
self.process_chat_events();
|
||||
if !self.search_index_rebuild_running {
|
||||
self.auto_save_due_post_editors();
|
||||
}
|
||||
@@ -2385,6 +2558,7 @@ impl BdsApp {
|
||||
&self.sidebar_scripts,
|
||||
&self.sidebar_templates,
|
||||
&self.sidebar_imports,
|
||||
&self.chat_conversations,
|
||||
active_post_filter,
|
||||
&self.media_filter,
|
||||
&self.sidebar_media_thumbs,
|
||||
@@ -2409,6 +2583,7 @@ impl BdsApp {
|
||||
&self.template_editors,
|
||||
&self.script_editors,
|
||||
&self.import_editors,
|
||||
&self.chat_editors,
|
||||
self.tags_view_state.as_ref(),
|
||||
self.settings_state.as_ref(),
|
||||
self.dashboard_state.as_ref(),
|
||||
@@ -2458,6 +2633,324 @@ impl BdsApp {
|
||||
|
||||
// ── Private helpers ──
|
||||
|
||||
fn active_chat_id(&self) -> Option<&str> {
|
||||
let id = self.active_tab.as_deref()?;
|
||||
self.tabs
|
||||
.iter()
|
||||
.any(|tab| tab.id == id && tab.tab_type == TabType::Chat)
|
||||
.then_some(id)
|
||||
}
|
||||
|
||||
fn active_chat_state_mut(&mut self) -> Option<&mut ChatEditorState> {
|
||||
let id = self.active_chat_id()?.to_string();
|
||||
self.chat_editors.get_mut(&id)
|
||||
}
|
||||
|
||||
fn refresh_chat_conversations(&mut self) {
|
||||
self.chat_conversations = self
|
||||
.db
|
||||
.as_ref()
|
||||
.and_then(|db| engine::chat::list_conversations(db.conn()).ok())
|
||||
.unwrap_or_default();
|
||||
}
|
||||
|
||||
fn chat_model_options(&self) -> Vec<ChatModelChoice> {
|
||||
let mut models = self
|
||||
.db
|
||||
.as_ref()
|
||||
.and_then(|db| engine::chat::list_models(db.conn()).ok())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|model| {
|
||||
let context = model.context_window.div_ceil(1_000).to_string();
|
||||
let output = model.max_output_tokens.div_ceil(1_000).to_string();
|
||||
let capability = t(
|
||||
self.ui_locale,
|
||||
if model.supports_tools {
|
||||
"chat.model.tools"
|
||||
} else {
|
||||
"chat.model.textOnly"
|
||||
},
|
||||
);
|
||||
ChatModelChoice {
|
||||
id: model.id,
|
||||
label: tw(
|
||||
self.ui_locale,
|
||||
"chat.model.option",
|
||||
&[
|
||||
("provider", &model.provider),
|
||||
("name", &model.name),
|
||||
("context", &context),
|
||||
("output", &output),
|
||||
("capability", &capability),
|
||||
],
|
||||
),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(db) = &self.db
|
||||
&& let Ok(settings) = ai::load_ai_settings(db.conn(), self.offline_mode)
|
||||
{
|
||||
if let Some(model) = settings.default_model
|
||||
&& !models.iter().any(|choice| choice.id == model)
|
||||
{
|
||||
models.push(ChatModelChoice {
|
||||
id: model.clone(),
|
||||
label: model,
|
||||
});
|
||||
}
|
||||
let endpoint_model = if self.offline_mode {
|
||||
settings.airplane_endpoint.model
|
||||
} else {
|
||||
settings.online_endpoint.model
|
||||
};
|
||||
if !endpoint_model.trim().is_empty()
|
||||
&& !models.iter().any(|choice| choice.id == endpoint_model)
|
||||
{
|
||||
models.push(ChatModelChoice {
|
||||
id: endpoint_model.clone(),
|
||||
label: endpoint_model,
|
||||
});
|
||||
}
|
||||
}
|
||||
models.sort_by(|left, right| left.label.cmp(&right.label));
|
||||
models.dedup_by(|left, right| left.id == right.id);
|
||||
models
|
||||
}
|
||||
|
||||
fn create_chat_conversation(&mut self) -> Task<Message> {
|
||||
let model = self
|
||||
.chat_model_options()
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|choice| choice.id);
|
||||
let title = model.as_deref().map_or_else(
|
||||
|| t(self.ui_locale, "chat.new"),
|
||||
|model| tw(self.ui_locale, "chat.newWithModel", &[("model", model)]),
|
||||
);
|
||||
let result = self
|
||||
.db
|
||||
.as_ref()
|
||||
.ok_or_else(|| "database unavailable".to_string())
|
||||
.and_then(|db| {
|
||||
engine::chat::create_conversation_titled(db.conn(), model.as_deref(), &title)
|
||||
.map_err(|error| error.to_string())
|
||||
});
|
||||
match result {
|
||||
Ok(conversation) => {
|
||||
self.refresh_chat_conversations();
|
||||
Task::done(Message::OpenTab(Tab {
|
||||
id: conversation.id,
|
||||
tab_type: TabType::Chat,
|
||||
title: conversation.title,
|
||||
is_transient: false,
|
||||
is_dirty: false,
|
||||
}))
|
||||
}
|
||||
Err(error) => {
|
||||
self.notify(ToastLevel::Error, &error);
|
||||
Task::none()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn send_active_chat_message(&mut self) -> Task<Message> {
|
||||
let Some(conversation_id) = self.active_chat_id().map(str::to_string) else {
|
||||
return Task::none();
|
||||
};
|
||||
let Some(project_id) = self
|
||||
.active_project
|
||||
.as_ref()
|
||||
.map(|project| project.id.clone())
|
||||
else {
|
||||
return Task::none();
|
||||
};
|
||||
let Some(data_dir) = self.data_dir.clone() else {
|
||||
return Task::none();
|
||||
};
|
||||
let Some(state) = self.chat_editors.get_mut(&conversation_id) else {
|
||||
return Task::none();
|
||||
};
|
||||
if state.streaming {
|
||||
return Task::none();
|
||||
}
|
||||
let content = state.input.text().trim().to_string();
|
||||
if content.is_empty() {
|
||||
return Task::none();
|
||||
}
|
||||
state.input = iced::widget::text_editor::Content::new();
|
||||
state.streaming = true;
|
||||
state.clear_streaming();
|
||||
state.active_tool = None;
|
||||
state.error = None;
|
||||
let db_path = self.db_path.clone();
|
||||
let offline_mode = self.offline_mode;
|
||||
let result_id = conversation_id.clone();
|
||||
Task::perform(
|
||||
async move {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let db = Database::open(&db_path).map_err(|error| error.to_string())?;
|
||||
engine::chat::send_chat_message(
|
||||
db.conn(),
|
||||
&data_dir,
|
||||
&project_id,
|
||||
offline_mode,
|
||||
&conversation_id,
|
||||
&content,
|
||||
engine::chat::ChatSendOptions::default(),
|
||||
)
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
},
|
||||
move |result| Message::ChatFinished {
|
||||
conversation_id: result_id.clone(),
|
||||
result,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn process_chat_events(&mut self) {
|
||||
let events = self.chat_events.try_iter().collect::<Vec<_>>();
|
||||
for event in events {
|
||||
match event {
|
||||
engine::chat::ChatEvent::Content {
|
||||
conversation_id,
|
||||
content,
|
||||
} => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&conversation_id) {
|
||||
state.set_streaming_content(content);
|
||||
}
|
||||
}
|
||||
engine::chat::ChatEvent::ToolStarted {
|
||||
conversation_id,
|
||||
name,
|
||||
} => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&conversation_id) {
|
||||
state.active_tool = Some(name);
|
||||
}
|
||||
}
|
||||
engine::chat::ChatEvent::ToolFinished {
|
||||
conversation_id, ..
|
||||
} => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&conversation_id) {
|
||||
state.active_tool = None;
|
||||
}
|
||||
}
|
||||
engine::chat::ChatEvent::Failed {
|
||||
conversation_id,
|
||||
message,
|
||||
} => {
|
||||
if let Some(state) = self.chat_editors.get_mut(&conversation_id) {
|
||||
state.error = Some(message);
|
||||
}
|
||||
}
|
||||
engine::chat::ChatEvent::Navigate {
|
||||
destination,
|
||||
entity_id,
|
||||
} => self.dispatch_chat_navigation(&destination, entity_id.as_deref()),
|
||||
engine::chat::ChatEvent::Started { .. }
|
||||
| engine::chat::ChatEvent::Finished { .. }
|
||||
| engine::chat::ChatEvent::Cancelled { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_chat_navigation(&mut self, destination: &str, entity_id: Option<&str>) {
|
||||
match destination {
|
||||
"toggle_sidebar" => {
|
||||
self.sidebar_visible = !self.sidebar_visible;
|
||||
return;
|
||||
}
|
||||
"toggle_panel" => {
|
||||
self.panel_visible = !self.panel_visible;
|
||||
return;
|
||||
}
|
||||
"toggle_assistant_sidebar" => {
|
||||
if self.sidebar_view == SidebarView::Chat {
|
||||
self.sidebar_visible = !self.sidebar_visible;
|
||||
} else {
|
||||
self.sidebar_view = SidebarView::Chat;
|
||||
self.sidebar_visible = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
self.sidebar_view = match destination {
|
||||
"posts" => SidebarView::Posts,
|
||||
"pages" => SidebarView::Pages,
|
||||
"media" => SidebarView::Media,
|
||||
"templates" => SidebarView::Templates,
|
||||
"scripts" => SidebarView::Scripts,
|
||||
"tags" => SidebarView::Tags,
|
||||
"chat" => SidebarView::Chat,
|
||||
"import" => SidebarView::Import,
|
||||
"git" => SidebarView::Git,
|
||||
"settings" => SidebarView::Settings,
|
||||
_ => return,
|
||||
};
|
||||
self.sidebar_visible = true;
|
||||
if destination == "settings" && entity_id.is_none() {
|
||||
self.open_singleton_tab(TabType::Settings, "common.settings");
|
||||
if self.settings_state.is_none() {
|
||||
self.settings_state = Some(self.hydrate_settings_state());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if destination == "tags" && entity_id.is_none() {
|
||||
self.open_singleton_tab(TabType::Tags, "tabBar.tags");
|
||||
return;
|
||||
}
|
||||
let Some(id) = entity_id else { return };
|
||||
let tab = self.db.as_ref().and_then(|db| match destination {
|
||||
"posts" => bds_core::db::queries::post::get_post_by_id(db.conn(), id)
|
||||
.ok()
|
||||
.map(|item| (TabType::Post, item.title)),
|
||||
"media" => bds_core::db::queries::media::get_media_by_id(db.conn(), id)
|
||||
.ok()
|
||||
.map(|item| {
|
||||
(
|
||||
TabType::Media,
|
||||
item.title.unwrap_or_else(|| item.original_name.clone()),
|
||||
)
|
||||
}),
|
||||
"templates" => bds_core::db::queries::template::get_template_by_id(db.conn(), id)
|
||||
.ok()
|
||||
.map(|item| (TabType::Templates, item.title)),
|
||||
"scripts" => bds_core::db::queries::script::get_script_by_id(db.conn(), id)
|
||||
.ok()
|
||||
.map(|item| (TabType::Scripts, item.title)),
|
||||
"chat" => engine::chat::get_conversation(db.conn(), id)
|
||||
.ok()
|
||||
.map(|item| (TabType::Chat, item.title)),
|
||||
_ => None,
|
||||
});
|
||||
let Some((tab_type, title)) = tab else {
|
||||
self.notify(
|
||||
ToastLevel::Error,
|
||||
&t(self.ui_locale, "chat.navigation.invalid"),
|
||||
);
|
||||
return;
|
||||
};
|
||||
let index = tabs::open_tab(
|
||||
&mut self.tabs,
|
||||
Tab {
|
||||
id: id.to_string(),
|
||||
tab_type,
|
||||
title,
|
||||
is_transient: false,
|
||||
is_dirty: false,
|
||||
},
|
||||
);
|
||||
if let Some(tab) = self.tabs.get(index).cloned() {
|
||||
self.active_tab = Some(tab.id.clone());
|
||||
self.load_editor_for_tab(&tab);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_ui_locale(&mut self, locale: UiLocale) {
|
||||
self.ui_locale = locale;
|
||||
self.locale_dropdown_open = false;
|
||||
@@ -6398,6 +6891,28 @@ impl BdsApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
TabType::Chat => {
|
||||
if !self.chat_editors.contains_key(&tab.id) {
|
||||
if self.settings_state.is_none() {
|
||||
self.settings_state = Some(self.hydrate_settings_state());
|
||||
}
|
||||
match (
|
||||
engine::chat::get_conversation(db.conn(), &tab.id),
|
||||
engine::chat::list_messages(db.conn(), &tab.id),
|
||||
) {
|
||||
(Ok(conversation), Ok(messages)) => {
|
||||
let models = self.chat_model_options();
|
||||
self.chat_editors.insert(
|
||||
tab.id.clone(),
|
||||
ChatEditorState::new(conversation, messages, models),
|
||||
);
|
||||
}
|
||||
(Err(error), _) | (_, Err(error)) => {
|
||||
self.notify(ToastLevel::Error, &error.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
TabType::Tags => {
|
||||
if self.tags_view_state.is_none() {
|
||||
let project_id = self
|
||||
@@ -9169,4 +9684,45 @@ mod tests {
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_ui_creates_reopens_renames_and_deletes_persistent_conversations() {
|
||||
let (db, project, tmp) = setup();
|
||||
let mut app = make_app(db, project, &tmp);
|
||||
|
||||
let _ = app.update(Message::ChatCreate);
|
||||
assert_eq!(app.chat_conversations.len(), 1);
|
||||
let conversation = app.chat_conversations[0].clone();
|
||||
let tab = Tab {
|
||||
id: conversation.id.clone(),
|
||||
tab_type: TabType::Chat,
|
||||
title: conversation.title,
|
||||
is_transient: false,
|
||||
is_dirty: false,
|
||||
};
|
||||
let _ = app.update(Message::OpenTab(tab));
|
||||
assert!(app.chat_editors.contains_key(&conversation.id));
|
||||
|
||||
let _ = app.update(Message::ChatRenameInputChanged("Research".to_string()));
|
||||
let _ = app.update(Message::ChatRename);
|
||||
assert_eq!(app.chat_conversations[0].title, "Research");
|
||||
assert_eq!(
|
||||
bds_core::engine::chat::get_conversation(
|
||||
app.db.as_ref().unwrap().conn(),
|
||||
&conversation.id,
|
||||
)
|
||||
.unwrap()
|
||||
.title,
|
||||
"Research"
|
||||
);
|
||||
|
||||
let _ = app.update(Message::ChatDelete(conversation.id.clone()));
|
||||
assert!(app.chat_conversations.is_empty());
|
||||
assert!(!app.chat_editors.contains_key(&conversation.id));
|
||||
assert!(
|
||||
bds_core::engine::chat::list_conversations(app.db.as_ref().unwrap().conn())
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
429
crates/bds-ui/src/views/chat_view.rs
Normal file
429
crates/bds-ui/src/views/chat_view.rs
Normal 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<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("");
|
||||
assert_eq!(safe, "[🖼 diagram](https://example.com/a.png)");
|
||||
assert_eq!(parse_safe_markdown(&safe).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod activity_bar;
|
||||
pub mod chat_view;
|
||||
pub mod dashboard;
|
||||
pub mod git;
|
||||
pub mod import_editor;
|
||||
|
||||
@@ -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,]
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user