Compare commits

...

7 Commits

19 changed files with 582 additions and 248 deletions

View File

@@ -1,5 +0,0 @@
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
is_user BOOL NOT NULL
);

View File

@@ -0,0 +1,12 @@
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
text TEXT NOT NULL,
is_user BOOL NOT NULL,
UNIQUE(id, chat_id)
);
CREATE INDEX idx_message_timestamp ON messages(timestamp);
CREATE INDEX idx_message_chat_id ON messages(chat_id);

View File

@@ -1,22 +1,29 @@
use anyhow::Result; use anyhow::Result;
use directories::ProjectDirs; use directories::ProjectDirs;
use sqlx::sqlite::SqliteConnectOptions; use sqlx::sqlite::SqliteConnectOptions;
use sqlx::Row; use sqlx::{Row, SqlitePool};
use sqlx::SqlitePool;
use tokio::fs; use tokio::fs;
use tonic::async_trait; use tonic::async_trait;
#[derive(Debug, sqlx::FromRow)] #[derive(Debug, sqlx::FromRow)]
pub struct ChatMessage { pub struct ChatMessageData {
pub id: i64, pub id: i64,
pub chat_id: i64,
pub text: String, pub text: String,
pub is_user: bool, pub is_user: bool,
} }
#[async_trait] #[async_trait]
pub trait ChatRepository { pub trait ChatRepository {
async fn save_message(&self, text: &str, is_user: &bool) -> Result<ChatMessage>; async fn save_message(
async fn get_latest_messages(&self) -> Result<Vec<ChatMessage>>; &self,
text: &str,
is_user: &bool,
chat_id: &i64,
) -> Result<ChatMessageData>;
async fn get_latest_messages(&self, chat_id: &i64, count: &i64)
-> Result<Vec<ChatMessageData>>;
async fn get_chat_ids(&self) -> Result<Box<[i64]>>;
} }
pub struct SqliteChatRepository { pub struct SqliteChatRepository {
@@ -51,31 +58,46 @@ impl SqliteChatRepository {
#[async_trait] #[async_trait]
impl ChatRepository for SqliteChatRepository { impl ChatRepository for SqliteChatRepository {
async fn save_message(&self, text: &str, is_user: &bool) -> Result<ChatMessage> { async fn save_message(
let result = sqlx::query_as::<_, ChatMessage>( &self,
text: &str,
is_user: &bool,
chat_id: &i64,
) -> Result<ChatMessageData> {
let result = sqlx::query_as::<_, ChatMessageData>(
r#" r#"
INSERT INTO messages (text, is_user) INSERT INTO messages (text, is_user, chat_id)
VALUES (?, ?) VALUES (?, ?, ?)
RETURNING id, text, is_user RETURNING id, chat_id, text, is_user
"#, "#,
) )
.bind(text) .bind(text)
.bind(is_user) .bind(is_user)
.bind(chat_id)
.fetch_one(&self.pool) .fetch_one(&self.pool)
.await .await
.inspect_err(|e| println!("sql error: {}", e))?; .inspect_err(|e| println!("sql error: {}", e))?;
Ok(result) Ok(result)
} }
async fn get_latest_messages(&self) -> Result<Vec<ChatMessage>> { async fn get_latest_messages(
&self,
chat_id: &i64,
count: &i64,
) -> Result<Vec<ChatMessageData>> {
// From all chat ids get the latest id.
let rows = sqlx::query( let rows = sqlx::query(
format!(
r#" r#"
SELECT * FROM ( SELECT * FROM (
SELECT id, text, is_user SELECT id, chat_id, text, is_user
FROM messages FROM messages
WHERE chat_id = {chat_id}
ORDER BY id DESC ORDER BY id DESC
LIMIT 10 LIMIT {count}
) AS subquery ORDER BY id ASC"#, ) AS subquery ORDER BY id ASC;"#
)
.as_str(),
) )
.fetch_all(&self.pool) .fetch_all(&self.pool)
.await .await
@@ -83,13 +105,29 @@ impl ChatRepository for SqliteChatRepository {
let messages = rows let messages = rows
.into_iter() .into_iter()
.map(|row| ChatMessage { .map(|row| ChatMessageData {
id: row.get(0), id: row.get(0),
text: row.get(1), chat_id: row.get(1),
is_user: row.get(2), text: row.get(2),
is_user: row.get(3),
}) })
.collect(); .collect();
Ok(messages) Ok(messages)
} }
async fn get_chat_ids(&self) -> Result<Box<[i64]>> {
let rows = sqlx::query("SELECT DISTINCT(chat_id) FROM messages ORDER BY chat_id DESC")
.fetch_all(&self.pool)
.await
.inspect_err(|e| println!("sql error: {}", e))?;
let ids: Vec<i64> = rows
.into_iter()
.map(|row| {
let i: i64 = row.get(0);
i
})
.collect();
Ok(ids.into_boxed_slice())
}
} }

View File

@@ -1,5 +1,8 @@
use crate::chatpersistence::{ChatMessage, ChatRepository}; use crate::chatpersistence::{ChatMessageData, ChatRepository};
use shared::ai::ai_daemon_server::AiDaemon; use anyhow::Result;
use genai::chat::{ChatMessage, ChatRequest};
use genai::Client;
use shared::ai::ai_service_server::AiService;
use shared::ai::{ use shared::ai::{
ChatHistoryRequest, ChatHistoryResponse, ChatMessage as CMessage, ChatRequest as CRequest, ChatHistoryRequest, ChatHistoryResponse, ChatMessage as CMessage, ChatRequest as CRequest,
ChatResponse as CResponse, DaemonStatusRequest, DaemonStatusResponse, ChatResponse as CResponse, DaemonStatusRequest, DaemonStatusResponse,
@@ -9,35 +12,60 @@ use tonic::{Code, Request, Response, Status};
pub struct DaemonServer { pub struct DaemonServer {
repo: Arc<dyn ChatRepository + Send + Sync>, repo: Arc<dyn ChatRepository + Send + Sync>,
client: Client,
} }
impl DaemonServer { impl DaemonServer {
pub fn new(repo: Arc<dyn ChatRepository + Send + Sync>) -> Self { pub fn new(repo: Arc<dyn ChatRepository + Send + Sync>, client: Client) -> Self {
Self { repo } Self {
repo: repo,
client: client,
}
} }
} }
#[tonic::async_trait] #[tonic::async_trait]
impl AiDaemon for DaemonServer { impl AiService for DaemonServer {
async fn chat(&self, request: Request<CRequest>) -> Result<Response<CResponse>, Status> { async fn chat(&self, request: Request<CRequest>) -> Result<Response<CResponse>, Status> {
let r = request.into_inner(); let r = request.into_inner();
let chat_id = id_or_new(self.repo.clone(), r.chat_id)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let mut messages = gather_history(self.repo.clone(), &chat_id)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
messages.push(ChatMessage::user(r.text()));
let model = "llama3.2:latest";
let response = self
.client
.exec_chat(model, ChatRequest::new(messages), None)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let user_message = message_to_dto( let user_message = message_to_dto(
&self &self
.repo .repo
.save_message(r.text(), &true) .save_message(r.text(), &true, &chat_id)
.await .await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?, .map_err(|e| Status::new(Code::Internal, e.to_string()))?,
); );
let response_text = format!("Pong: {}", r.text()); let response_text = match response.first_text() {
Some(t) => t,
None => "[No response from AI]",
};
println!("User: {}", r.text());
println!("AI: {}", response_text);
let ai_message = message_to_dto( let ai_message = message_to_dto(
&self &self
.repo .repo
.save_message(response_text.as_str(), &false) .save_message(response_text, &false, &chat_id)
.await .await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?, .map_err(|e| Status::new(Code::Internal, e.to_string()))?,
); );
let response = CResponse { let response = CResponse {
chat_id: 1, chat_id: ai_message.chat_id,
messages: vec![user_message, ai_message], messages: vec![user_message, ai_message],
}; };
return Ok(Response::new(response)); return Ok(Response::new(response));
@@ -45,16 +73,19 @@ impl AiDaemon for DaemonServer {
async fn chat_history( async fn chat_history(
&self, &self,
_: Request<ChatHistoryRequest>, request: Request<ChatHistoryRequest>,
) -> Result<Response<ChatHistoryResponse>, Status> { ) -> Result<Response<ChatHistoryResponse>, Status> {
let chat_id = get_latest_chat_id(self.repo.clone(), request.into_inner().chat_id)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let messages = self let messages = self
.repo .repo
.get_latest_messages() .get_latest_messages(&chat_id, &20)
.await .await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?; .map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let response = ChatHistoryResponse { let response = ChatHistoryResponse {
chat_id: 1, chat_id: chat_id,
history: messages.iter().map(|m| message_to_dto(m)).collect(), history: messages.iter().map(|m| message_to_dto(m)).collect(),
}; };
Ok(Response::new(response)) Ok(Response::new(response))
@@ -73,10 +104,45 @@ impl AiDaemon for DaemonServer {
} }
} }
pub fn message_to_dto(msg: &ChatMessage) -> CMessage { pub fn message_to_dto(msg: &ChatMessageData) -> CMessage {
CMessage { CMessage {
id: msg.id, id: msg.id,
chat_id: msg.chat_id,
text: msg.text.clone(), text: msg.text.clone(),
is_user: msg.is_user, is_user: msg.is_user,
} }
} }
async fn gather_history(
repo: Arc<dyn ChatRepository + Send + Sync>,
chat_id: &i64,
) -> Result<Vec<ChatMessage>> {
let messages = repo.get_latest_messages(chat_id, &10).await?;
Ok(messages
.iter()
.map(|m| match m.is_user {
true => ChatMessage::assistant(m.text.clone()),
false => ChatMessage::user(m.text.clone()),
})
.collect())
}
async fn get_latest_chat_id(
repo: Arc<dyn ChatRepository + Send + Sync>,
chat_id: Option<i64>,
) -> Result<i64> {
Ok(match chat_id {
Some(i) => i,
None => repo.get_chat_ids().await?.get(0).copied().unwrap_or(0),
})
}
async fn id_or_new(
repo: Arc<dyn ChatRepository + Send + Sync>,
chat_id: Option<i64>,
) -> Result<i64> {
Ok(match chat_id {
Some(i) => i,
None => repo.get_chat_ids().await?.get(0).copied().unwrap_or(0) + 1,
})
}

View File

@@ -3,41 +3,28 @@ mod daemongrpc;
use std::sync::Arc; use std::sync::Arc;
use genai::chat::{ChatMessage, ChatRequest};
use genai::Client; use genai::Client;
use shared::ai::ai_daemon_server::AiDaemonServer; use shared::ai::ai_service_server::AiServiceServer;
use tonic::transport::Server; use tonic::transport::Server;
use chatpersistence::SqliteChatRepository; use chatpersistence::SqliteChatRepository;
use daemongrpc::DaemonServer; use daemongrpc::DaemonServer;
async fn prompt_ollama(
client: &Client,
model: &str,
prompt: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let chat_req = ChatRequest::new(vec![ChatMessage::user(prompt)]);
let chat_res = client.exec_chat(model, chat_req, None).await?;
let output = chat_res
.first_text()
.unwrap_or("No response content!")
.to_string();
Ok(output)
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> { async fn main() -> Result<(), Box<dyn std::error::Error>> {
let chat_repo = SqliteChatRepository::new().await?; let chat_repo = SqliteChatRepository::new().await?;
let client = Client::default();
let addr_s = "[::1]:50051"; let addr_s = "[::1]:50051";
let addr = addr_s.parse().unwrap(); let addr = addr_s.parse().unwrap();
let daemon = DaemonServer::new(Arc::new(chat_repo)); let daemon = DaemonServer::new(Arc::new(chat_repo), client);
let reflection_service = tonic_reflection::server::Builder::configure() let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(shared::ai::FILE_DESCRIPTOR_SET) .register_encoded_file_descriptor_set(shared::ai::FILE_DESCRIPTOR_SET)
.build_v1()?; .build_v1()?;
println!("Started daemon at {}", addr_s); println!("Started daemon at {}", addr_s);
Server::builder() Server::builder()
.add_service(AiDaemonServer::new(daemon)) .add_service(AiServiceServer::new(daemon))
.add_service(reflection_service) .add_service(reflection_service)
.serve(addr) .serve(addr)
.await?; .await?;

View File

@@ -13,6 +13,28 @@ pub mod chatmessage {
pub chat_id: Option<i64>, pub chat_id: Option<i64>,
pub history: Vec<Message>, pub history: Vec<Message>,
} }
pub enum TauriCommand {
Chat,
SetChatId,
ChatHistory,
DaemonState,
ToggleDarkMode,
TogglePopup,
}
impl TauriCommand {
pub fn as_str(&self) -> &'static str {
match self {
TauriCommand::TogglePopup => "toggle_popup",
TauriCommand::Chat => "chat",
TauriCommand::SetChatId => "set_chat_id",
TauriCommand::ChatHistory => "chat_history",
TauriCommand::DaemonState => "daemon_state",
TauriCommand::ToggleDarkMode => "toggle_dark_mode",
}
}
}
} }
pub mod daemon { pub mod daemon {

View File

@@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package ai_daemon; package ai_daemon;
service AiDaemon { service AiService {
rpc Chat(ChatRequest) returns (ChatResponse); rpc Chat(ChatRequest) returns (ChatResponse);
rpc ChatHistory(ChatHistoryRequest) returns (ChatHistoryResponse); rpc ChatHistory(ChatHistoryRequest) returns (ChatHistoryResponse);
rpc DaemonStatus(DaemonStatusRequest) returns (DaemonStatusResponse); rpc DaemonStatus(DaemonStatusRequest) returns (DaemonStatusResponse);
@@ -9,6 +9,7 @@ service AiDaemon {
message ChatMessage { message ChatMessage {
int64 id = 1; int64 id = 1;
int64 chat_id = 2;
string text = 10; string text = 10;
bool is_user = 20; bool is_user = 20;
} }

View File

@@ -3,8 +3,5 @@
"identifier": "default", "identifier": "default",
"description": "Capability for the main window", "description": "Capability for the main window",
"windows": ["main"], "windows": ["main"],
"permissions": [ "permissions": ["core:default", "opener:default"]
"core:default",
"opener:default"
]
} }

View File

@@ -1,14 +1,6 @@
{ {
"identifier": "desktop-capability", "identifier": "desktop-capability",
"platforms": [ "platforms": ["macOS", "windows", "linux"],
"macOS", "windows": ["main", "dashboard", "popup"],
"windows", "permissions": ["global-shortcut:default", "core:event:allow-listen"]
"linux"
],
"windows": [
"main"
],
"permissions": [
"global-shortcut:default"
]
} }

View File

@@ -1,3 +1,4 @@
use serde::Serialize;
use tauri::{Emitter, Manager, State}; use tauri::{Emitter, Manager, State};
use feshared::{ use feshared::{
@@ -28,19 +29,19 @@ pub fn toggle_popup(app_handle: tauri::AppHandle) {
} }
#[tauri::command] #[tauri::command]
pub async fn chat( pub async fn chat(state: State<'_, AppState>, prompt: String) -> Result<Vec<Message>, String> {
state: State<'_, AppState>,
prompt: String,
chat_id: Option<i64>,
) -> Result<Vec<Message>, String> {
let mut client = state.grpc_client.lock().await; let mut client = state.grpc_client.lock().await;
let cid = state.current_chat_id.lock().await.clone();
let request = tonic::Request::new(ChatRequest { let request = tonic::Request::new(ChatRequest {
chat_id: chat_id, chat_id: cid,
text: Some(prompt), text: Some(prompt),
}); });
match client.chat(request).await { match client.chat(request).await {
Ok(response) => { Ok(response) => {
let r = response.into_inner(); let r = response.into_inner();
let mut cid = state.current_chat_id.lock().await;
*cid = Some(r.chat_id);
println!("CID={}", r.chat_id);
r.messages.iter().for_each(|m| { r.messages.iter().for_each(|m| {
if m.is_user { if m.is_user {
println!(">>> {}", m.text) println!(">>> {}", m.text)
@@ -65,19 +66,30 @@ pub async fn chat(
} }
#[tauri::command] #[tauri::command]
pub async fn chat_history( pub async fn set_chat_id(
state: State<'_, AppState>, state: State<'_, AppState>,
chat_id: Option<i64>, chat_id: Option<i64>,
) -> Result<MessageHistory, String> { ) -> Result<Option<i64>, String> {
let mut cid = state.current_chat_id.lock().await;
*cid = chat_id;
Ok(chat_id)
}
#[tauri::command]
pub async fn chat_history(state: State<'_, AppState>) -> Result<MessageHistory, String> {
let mut client = state.grpc_client.lock().await; let mut client = state.grpc_client.lock().await;
let chat_id = state.current_chat_id.lock().await.clone();
let result = client let result = client
.chat_history(ChatHistoryRequest { chat_id: None }) .chat_history(ChatHistoryRequest { chat_id: chat_id })
.await; .await;
match result { match result {
Ok(response) => { Ok(response) => {
let r = response.into_inner(); let r = response.into_inner();
let mut cid = state.current_chat_id.lock().await;
*cid = Some(r.chat_id);
println!("CID={}", r.chat_id);
Ok(MessageHistory { Ok(MessageHistory {
chat_id: None, chat_id: Some(r.chat_id),
history: r history: r
.history .history
.iter() .iter()
@@ -113,3 +125,26 @@ pub async fn daemon_state(state: State<'_, AppState>) -> Result<DaemonState, Str
}), }),
} }
} }
#[derive(Clone, Serialize)]
struct DarkMode {
is_dark_mode: bool,
}
#[tauri::command]
pub async fn toggle_dark_mode(
state: State<'_, AppState>,
handle: tauri::AppHandle,
) -> Result<bool, String> {
let mut config = state.config.lock().await;
config.dark_mode = !config.dark_mode;
handle
.emit(
"dark-mode-changed",
DarkMode {
is_dark_mode: config.dark_mode,
},
)
.unwrap();
Ok(config.dark_mode)
}

View File

@@ -6,30 +6,38 @@ mod commands;
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState}; use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use commands::{chat, chat_history, daemon_state, toggle_popup}; use commands::{chat, chat_history, daemon_state, set_chat_id, toggle_dark_mode, toggle_popup};
use shared::ai::ai_daemon_client::AiDaemonClient; use shared::ai::ai_service_client::AiServiceClient;
pub struct AppConfig {
dark_mode: bool,
}
pub struct AppState { pub struct AppState {
grpc_client: Mutex<AiDaemonClient<tonic::transport::Channel>>, grpc_client: Mutex<AiServiceClient<tonic::transport::Channel>>,
current_chat: Mutex<Option<i64>>, config: Mutex<AppConfig>,
current_chat_id: Mutex<Option<i64>>,
} }
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let channel = tonic::transport::Channel::from_static("http://[::1]:50051").connect_lazy(); let channel = tonic::transport::Channel::from_static("http://[::1]:50051").connect_lazy();
let client = AiDaemonClient::new(channel); let client = AiServiceClient::new(channel);
tauri::Builder::default() tauri::Builder::default()
.manage(AppState { .manage(AppState {
grpc_client: Mutex::new(client), grpc_client: Mutex::new(client),
current_chat: Mutex::new(None), config: Mutex::new(AppConfig { dark_mode: true }),
current_chat_id: Mutex::new(None),
}) })
.plugin(tauri_plugin_global_shortcut::Builder::new().build()) .plugin(tauri_plugin_global_shortcut::Builder::new().build())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
toggle_popup, toggle_popup,
chat_history, chat_history,
set_chat_id,
chat, chat,
daemon_state daemon_state,
toggle_dark_mode,
]) ])
.setup(|app| { .setup(|app| {
/* Auto-hide popup when focus is lost /* Auto-hide popup when focus is lost

View File

@@ -22,8 +22,8 @@
"label": "popup", "label": "popup",
"title": "AI Quick Action", "title": "AI Quick Action",
"url": "/popup", "url": "/popup",
"width": 800, "width": 960,
"height": 400, "height": 720,
"decorations": false, "decorations": false,
"transparent": true, "transparent": true,
"alwaysOnTop": true, "alwaysOnTop": true,

View File

@@ -1,6 +1,6 @@
use std::time::Duration; use std::time::Duration;
use feshared::daemon::DaemonState; use feshared::{chatmessage::TauriCommand, daemon::DaemonState};
use leptos::{prelude::*, reactive::spawn_local}; use leptos::{prelude::*, reactive::spawn_local};
use leptos_router::{ use leptos_router::{
components::{Route, Router, Routes}, components::{Route, Router, Routes},
@@ -8,8 +8,12 @@ use leptos_router::{
}; };
use wasm_bindgen::JsValue; use wasm_bindgen::JsValue;
use crate::bridge::invoke; use crate::popup::PopupView;
use crate::popup::Popup; use crate::{bridge::invoke_js, components::DarkModeToggle};
use crate::{
bridge::invoke_typed,
components::{DaemonProvider, ThemeProvider},
};
pub const BTN_PRIMARY: &str = "bg-slate-300 hover:bg-slate-400 dark:bg-slate-800 hover:dark-bg-slate-700 px-4 py-2 rounded-md"; pub const BTN_PRIMARY: &str = "bg-slate-300 hover:bg-slate-400 dark:bg-slate-800 hover:dark-bg-slate-700 px-4 py-2 rounded-md";
@@ -19,7 +23,7 @@ pub fn App() -> impl IntoView {
<Router> <Router>
<Routes fallback=|| view! { "Page not found."}> <Routes fallback=|| view! { "Page not found."}>
<Route path=path!("/") view=Dashboard /> <Route path=path!("/") view=Dashboard />
<Route path=path!("/popup") view=Popup /> <Route path=path!("/popup") view=PopupView />
</Routes> </Routes>
</Router> </Router>
} }
@@ -30,17 +34,19 @@ fn Dashboard() -> impl IntoView {
let on_click = move |_ev: leptos::ev::MouseEvent| { let on_click = move |_ev: leptos::ev::MouseEvent| {
spawn_local(async move { spawn_local(async move {
let empty_args = serde_wasm_bindgen::to_value(&serde_json::json!({})).unwrap(); let empty_args = serde_wasm_bindgen::to_value(&serde_json::json!({})).unwrap();
invoke("toggle_popup", empty_args).await; invoke_js(TauriCommand::TogglePopup, empty_args).await;
}); });
}; };
view! { view! {
<ThemeProvider> <ThemeProvider>
<div class="fixed left-4 bottom-4"> <DaemonProvider>
<DaemonStatusIndicator /> <div class="min-h-screen w-screen bg-white dark:bg-zinc-900 text-gray-950 dark:text-white">
</div>
<main class="min-h-screen w-screen bg-white dark:bg-zinc-900 text-gray-950 dark:text-white p-3">
<button class=BTN_PRIMARY on:click=on_click>Open chat</button> <button class=BTN_PRIMARY on:click=on_click>Open chat</button>
</main> </div>
</DaemonProvider>
<div class="fixed bottom-0 right-0 p-2">
<DarkModeToggle />
</div>
</ThemeProvider> </ThemeProvider>
} }
} }
@@ -54,8 +60,7 @@ pub fn DaemonStatusIndicator() -> impl IntoView {
); );
let status = LocalResource::new(move || async move { let status = LocalResource::new(move || async move {
poll_count.get(); poll_count.get();
let val = invoke("daemon_state", JsValue::NULL).await; let s: DaemonState = invoke_typed(TauriCommand::DaemonState, JsValue::NULL).await;
let s: DaemonState = serde_wasm_bindgen::from_value(val).unwrap();
s s
}); });
@@ -88,29 +93,3 @@ pub fn DaemonStatusIndicator() -> impl IntoView {
</div> </div>
} }
} }
#[component]
pub fn ThemeProvider(children: Children) -> impl IntoView {
let (is_dark, set_dark) = signal(false);
Effect::new(move |_| {
let el = document()
.document_element()
.expect("HTML element not found!");
if is_dark.get() {
let _ = el.set_attribute("class", "dark");
} else {
let _ = el.set_attribute("class", "");
}
});
view! {
<div class="min-h-screen transition-colors duration-500">
<button
on:click=move |_| set_dark.update(|v| *v = !*v)
class="fixed top-4 right-4 p-2 bg-slate-200 dark:bg-slate-800 rounded-full">
{move || if is_dark.get() { "🌙" } else { "☀️" }}
</button>
{children()}
</div>
}
}

View File

@@ -1,6 +1,41 @@
use feshared::chatmessage::TauriCommand;
use serde::{de::DeserializeOwned, Deserialize};
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
#[wasm_bindgen] #[wasm_bindgen]
extern "C" { extern "C" {
#[wasm_bindgen(js_namespace = ["window", "__TAURI__", "core"])] #[wasm_bindgen(js_namespace = ["window", "__TAURI__", "core"])]
pub async fn invoke(cmd: &str, args: JsValue) -> JsValue; async fn invoke(cmd: &str, args: JsValue) -> JsValue;
#[wasm_bindgen(js_namespace = ["window", "__TAURI__", "event"])]
pub async fn listen(event: &str, handler: &Closure<dyn FnMut(JsValue)>) -> JsValue;
}
pub async fn invoke_js(cmd: TauriCommand, args: JsValue) -> JsValue {
invoke(cmd.as_str(), args).await
}
pub async fn invoke_typed<T>(cmd: TauriCommand, args: JsValue) -> T
where
T: DeserializeOwned,
{
let response = invoke(cmd.as_str(), args).await;
let result: T = serde_wasm_bindgen::from_value(response).unwrap();
result
}
pub fn event_handler<T, F>(callback: F) -> Closure<dyn FnMut(JsValue)>
where
T: DeserializeOwned + 'static,
F: Fn(T) + 'static,
{
Closure::new(move |val: JsValue| {
#[derive(Deserialize)]
struct TauriEvent<T> {
payload: T,
}
if let Ok(wrapper) = serde_wasm_bindgen::from_value::<TauriEvent<T>>(val) {
callback(wrapper.payload)
}
})
} }

125
frontend/src/components.rs Normal file
View File

@@ -0,0 +1,125 @@
use std::time::Duration;
use feshared::{chatmessage::TauriCommand, daemon::DaemonState};
use leptos::{component, prelude::*, reactive::spawn_local, view, IntoView};
use serde::{Deserialize, Serialize};
use wasm_bindgen::JsValue;
use crate::bridge::{event_handler, invoke_js, invoke_typed, listen};
#[component]
pub fn DaemonProvider(children: ChildrenFn) -> impl IntoView {
let (poll_count, set_pool_count) = signal(0);
set_interval(
move || set_pool_count.update(|v| *v += 1),
Duration::from_secs(1),
);
let status_res = LocalResource::new(move || async move {
poll_count.get();
let s: DaemonState = invoke_typed(TauriCommand::DaemonState, JsValue::NULL).await;
s
});
let is_daemon_ok = Memo::new(move |_| status_res.get().map(|s| (s.is_ok, s.error)));
provide_context(status_res);
move || match is_daemon_ok.get() {
Some((true, _)) => children().into_any(),
Some((false, err)) => view! { <DaemonErrorStatus error=err/> }.into_any(),
None => view! { <p>Connecting...</p> }.into_any(),
}
}
#[component]
pub fn DaemonErrorStatus(error: Option<String>) -> impl IntoView {
view! {
<div class="w-screen h-screen
text-gray-950 dark:text-white
bg-white dark:bg-zinc-900
flex justify-center items-center">
<div class="text-zinc-100 dark:text-zinc-800 fixed w-full">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" />
</svg>
</div>
<span class="fixed">{ error.unwrap_or("Daemon error!".to_string()) } </span>
</div>
}
}
#[derive(Deserialize, Serialize, Clone)]
pub struct DarkMode {
is_dark_mode: bool,
}
#[component]
pub fn ThemeProvider(children: Children) -> impl IntoView {
let (is_dark, set_dark) = signal(true);
Effect::new(move |_| {
spawn_local(async move {
let hndlr = event_handler(move |mode: DarkMode| {
set_dark.set(mode.is_dark_mode);
});
// TODO use on_cleanup to call the unlisten JS function.
let unlisten = listen("dark-mode-changed", &hndlr).await;
hndlr.forget()
});
});
Effect::new(move |_| {
let el = document()
.document_element()
.expect("HTML element not found!");
if is_dark.get() {
let _ = el.set_attribute("class", "dark");
} else {
let _ = el.set_attribute("class", "");
}
});
view! {
{children()}
}
}
#[component]
pub fn DarkModeToggle() -> impl IntoView {
let toggle_dark_mode = |_ev: leptos::ev::MouseEvent| {
spawn_local(async {
let _ = invoke_js(TauriCommand::ToggleDarkMode, JsValue::UNDEFINED).await;
});
};
view! {
<div on:click=toggle_dark_mode class="text-gray-600 dark:text-gray-600">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
<path stroke-linecap="round" stroke-linejoin="round" d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z" />
</svg>
</div>
}
}
#[component]
pub fn ConfirmDialog(
is_open: ReadSignal<bool>,
on_confirm: Callback<()>,
on_cancel: Callback<()>,
title: String,
message: String,
) -> impl IntoView {
view! {
<Show when=move || is_open.get()>
<div class="fixed inset-0 z-50 flex items-center justify-center backdrop-blur text-zinc-950 dark:text-white">
<div class="flex flex-col items-center justify-center p-4 rounded-lg bg-white/30 dark:bg-black/30">
<h3 class="text-lg font-bold mb-2">{ title.clone() }</h3>
<p>{ message.clone() }</p>
<div>
<button class="primary-button m-3" on:click=move |_| on_confirm.run(())>Confirm</button>
<button class="primary-button m-3" on:click=move |_| on_cancel.run(())>Cancel</button>
</div>
</div>
</div>
</Show>
}
}

View File

@@ -1,5 +1,6 @@
mod app; mod app;
mod bridge; mod bridge;
mod components;
mod popup; mod popup;
use app::*; use app::*;

View File

@@ -1,30 +1,45 @@
use crate::{ use crate::{
app::{DaemonStatusIndicator, ThemeProvider}, bridge::{invoke_js, invoke_typed},
bridge::invoke, components::{ConfirmDialog, DaemonProvider, DarkModeToggle, ThemeProvider},
};
use feshared::{
chatmessage::{Message, MessageHistory, TauriCommand},
daemon::DaemonState,
}; };
use feshared::chatmessage::{Message, MessageHistory};
use leptos::{ev::keydown, html::Input, prelude::*}; use leptos::{ev::keydown, html::Input, prelude::*};
use wasm_bindgen::{prelude::Closure, JsCast, JsValue}; use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use wasm_bindgen_futures::spawn_local; use wasm_bindgen_futures::spawn_local;
#[component]
pub fn PopupView() -> impl IntoView {
view! {<ThemeProvider>
<DaemonProvider>
<Popup />
</DaemonProvider>
</ThemeProvider>
}
}
#[component] #[component]
pub fn Popup() -> impl IntoView { pub fn Popup() -> impl IntoView {
// Prompt signals and and action // Prompt signals and and action
let prompt_input_ref = NodeRef::<Input>::new(); let prompt_input_ref = NodeRef::<Input>::new();
let (prompt_text, set_prompt_text) = signal(String::new()); let (prompt_text, set_prompt_text) = signal(String::new());
let (messages, set_messages) = signal(Vec::<Message>::new()); let (messages, set_messages) = signal(Vec::<Message>::new());
let status_res =
use_context::<LocalResource<DaemonState>>().expect("No daemon connection context!");
let init_history = Action::new_local(|(): &()| async move { let init_history = Action::new_local(|(): &()| async move {
let response = invoke( let history: MessageHistory =
"chat_history", invoke_typed(TauriCommand::ChatHistory, JsValue::UNDEFINED).await;
serde_wasm_bindgen::to_value(&serde_json::json!({"chat_id": 1})).unwrap(),
)
.await;
let history: MessageHistory = serde_wasm_bindgen::from_value(response).unwrap();
history history
}); });
Effect::new(move |_| { Effect::new(move |prev_status: Option<bool>| {
let current_ok = status_res.get().map(|s| s.is_ok).unwrap_or(false);
if current_ok && prev_status != Some(true) {
init_history.dispatch(()); init_history.dispatch(());
}
current_ok
}); });
Effect::new(move |_| { Effect::new(move |_| {
if let Some(mut dat) = init_history.value().get() { if let Some(mut dat) = init_history.value().get() {
@@ -32,16 +47,27 @@ pub fn Popup() -> impl IntoView {
} }
}); });
let set_chat_id_action = Action::new_local(|chat_id: &Option<i64>| {
let cid = chat_id.clone();
async move {
let result: Option<i64> = invoke_typed(
TauriCommand::SetChatId,
serde_wasm_bindgen::to_value(&serde_json::json!({"chat_id": cid})).unwrap(),
)
.await;
result
}
});
// Action that calls the chat action on the daemon // Action that calls the chat action on the daemon
let prompt_action = Action::new_local(|prompt: &String| { let prompt_action = Action::new_local(|prompt: &String| {
let prompt = prompt.clone(); let prompt = prompt.clone();
async move { async move {
let response = invoke( let result: Vec<Message> = invoke_typed(
"chat", TauriCommand::Chat,
serde_wasm_bindgen::to_value(&serde_json::json!({"prompt": prompt})).unwrap(), serde_wasm_bindgen::to_value(&serde_json::json!({"prompt": prompt})).unwrap(),
) )
.await; .await;
let result: Vec<Message> = serde_wasm_bindgen::from_value(response).unwrap();
result result
} }
}); });
@@ -71,17 +97,31 @@ pub fn Popup() -> impl IntoView {
let _ = window_event_listener(keydown, move |ev| { let _ = window_event_listener(keydown, move |ev| {
if ev.key() == "Escape" { if ev.key() == "Escape" {
spawn_local(async move { spawn_local(async move {
let _ = invoke("toggle_popup", JsValue::UNDEFINED).await; let _ = invoke_js(TauriCommand::TogglePopup, JsValue::UNDEFINED).await;
}); });
} }
}); });
let (show_new_chat_confirm, set_new_chat_confirm) = signal(false);
let new_chat = move |_: ()| {
set_messages.set(Vec::<Message>::new());
// TODO add callback to the action, and clear chat and close dialog in the callback!
set_chat_id_action.dispatch(None);
set_new_chat_confirm.set(false);
};
view! { view! {
<ThemeProvider> <ConfirmDialog
<main class="rounded-lg bg-white dark:bg-zinc-900 text-zinc-950 dark:text-white"> is_open=show_new_chat_confirm
<div class="max-h-screen p-2 flex flex-col"> on_confirm=Callback::new(new_chat)
on_cancel=Callback::new(move |_| set_new_chat_confirm.set(false))
title="Open a new chat?".to_string()
message="Current chat is stored".to_string() />
<div class="flex flex-col rounded-lg bg-white dark:bg-zinc-900 text-zinc-950 dark:text-white h-screen w-full">
<header class="relative p-3">
<input <input
class="flex-none p-3 mb-5 rounded-lg bg-zinc-200 dark:bg-zinc-950" class="w-full p-3 rounded-lg bg-zinc-200 dark:bg-zinc-950"
type="text" type="text"
node_ref=prompt_input_ref node_ref=prompt_input_ref
placeholder="Prompt..." placeholder="Prompt..."
@@ -95,7 +135,13 @@ pub fn Popup() -> impl IntoView {
} }
prop:value=prompt_text prop:value=prompt_text
/> />
<div class="flex-auto overflow-y-auto"> <button class="absolute py-1 px-2 right-5 mt-2
rounded-full
dark:bg-slate-800
dark:hover:bg-slate-600"
on:click=move |_| set_new_chat_confirm.set(true)>+</button>
</header>
<main class="flex-grow overflow-y-auto p-4">
<div class="flex flex-col"> <div class="flex flex-col">
<For each=move || messages.get() <For each=move || messages.get()
key=|msg| msg.id key=|msg| msg.id
@@ -104,12 +150,8 @@ pub fn Popup() -> impl IntoView {
<div class=if msg.is_user {"msg msg-user"} else {"msg msg-model"}>{msg.text}</div> <div class=if msg.is_user {"msg msg-user"} else {"msg msg-model"}>{msg.text}</div>
</For> </For>
</div> </div>
</div>
<div class="flex-none pt-2">
<DaemonStatusIndicator/>
</div>
</div>
</main> </main>
</ThemeProvider> <div class="fixed bottom-0 right-0 p-2"><DarkModeToggle /></div>
</div>
} }
} }

View File

@@ -4,7 +4,7 @@
@layer components { @layer components {
.msg { .msg {
@apply rounded-lg px-3 py-2 dark:bg-gray-800 max-w-[75%]; @apply rounded-lg mb-5 px-3 py-2 dark:bg-gray-800 max-w-[75%];
} }
.msg-model { .msg-model {
@@ -14,6 +14,10 @@
.msg-user { .msg-user {
@apply self-end bg-slate-200 dark:bg-zinc-800; @apply self-end bg-slate-200 dark:bg-zinc-800;
} }
.primary-button {
@apply bg-blue-300 dark:bg-gray-800 rounded-lg p-3;
}
} }
body { body {
@@ -21,25 +25,6 @@ body {
margin: 0; margin: 0;
} }
.dark-input {
padding: 12px 20px;
margin: 8px 0;
/* Colors & Background */
background-color: #1e1e1e;
color: #ffffff;
border: 1px solid #333333;
border-radius: 8px; /* Soft rounded corners */
/* Typography */
font-family: "Inter", sans-serif;
font-size: 16px;
/* Smooth Transition */
transition: all 0.3s ease;
outline: none;
}
@keyframes slideIn { @keyframes slideIn {
from { from {
opacity: 0; opacity: 0;

View File

@@ -579,20 +579,20 @@
.sticky { .sticky {
position: sticky; position: sticky;
} }
.top-4 { .inset-0 {
top: calc(var(--spacing) * 4); inset: calc(var(--spacing) * 0);
}
.right-0 {
right: calc(var(--spacing) * 0);
} }
.right-2 { .right-2 {
right: calc(var(--spacing) * 2); right: calc(var(--spacing) * 2);
} }
.right-4 { .right-5 {
right: calc(var(--spacing) * 4); right: calc(var(--spacing) * 5);
} }
.bottom-4 { .bottom-0 {
bottom: calc(var(--spacing) * 4); bottom: calc(var(--spacing) * 0);
}
.left-4 {
left: calc(var(--spacing) * 4);
} }
.isolate { .isolate {
isolation: isolate; isolation: isolate;
@@ -675,6 +675,9 @@
.m-0 { .m-0 {
margin: calc(var(--spacing) * 0); margin: calc(var(--spacing) * 0);
} }
.m-3 {
margin: calc(var(--spacing) * 3);
}
.-mx-1 { .-mx-1 {
margin-inline: calc(var(--spacing) * -1); margin-inline: calc(var(--spacing) * -1);
} }
@@ -690,11 +693,14 @@
.mt-1 { .mt-1 {
margin-top: calc(var(--spacing) * 1); margin-top: calc(var(--spacing) * 1);
} }
.mt-2 {
margin-top: calc(var(--spacing) * 2);
}
.mt-8 { .mt-8 {
margin-top: calc(var(--spacing) * 8); margin-top: calc(var(--spacing) * 8);
} }
.mb-5 { .mb-2 {
margin-bottom: calc(var(--spacing) * 5); margin-bottom: calc(var(--spacing) * 2);
} }
.mb-8 { .mb-8 {
margin-bottom: calc(var(--spacing) * 8); margin-bottom: calc(var(--spacing) * 8);
@@ -777,10 +783,6 @@
.field-sizing-fixed { .field-sizing-fixed {
field-sizing: fixed; field-sizing: fixed;
} }
.size-3 {
width: calc(var(--spacing) * 3);
height: calc(var(--spacing) * 3);
}
.size-3\.5 { .size-3\.5 {
width: calc(var(--spacing) * 3.5); width: calc(var(--spacing) * 3.5);
height: calc(var(--spacing) * 3.5); height: calc(var(--spacing) * 3.5);
@@ -1287,9 +1289,6 @@
.justify-items-stretch { .justify-items-stretch {
justify-items: stretch; justify-items: stretch;
} }
.gap-1 {
gap: calc(var(--spacing) * 1);
}
.gap-1\.5 { .gap-1\.5 {
gap: calc(var(--spacing) * 1.5); gap: calc(var(--spacing) * 1.5);
} }
@@ -1560,9 +1559,6 @@
.border-\[\#fbf0df\] { .border-\[\#fbf0df\] {
border-color: #fbf0df; border-color: #fbf0df;
} }
.border-zinc-200 {
border-color: var(--color-zinc-200);
}
.bg-\[\#1a1a1a\] { .bg-\[\#1a1a1a\] {
background-color: #1a1a1a; background-color: #1a1a1a;
} }
@@ -1578,9 +1574,6 @@
.bg-red-600 { .bg-red-600 {
background-color: var(--color-red-600); background-color: var(--color-red-600);
} }
.bg-slate-200 {
background-color: var(--color-slate-200);
}
.bg-slate-300 { .bg-slate-300 {
background-color: var(--color-slate-300); background-color: var(--color-slate-300);
} }
@@ -1590,6 +1583,12 @@
.bg-white { .bg-white {
background-color: var(--color-white); background-color: var(--color-white);
} }
.bg-white\/30 {
background-color: color-mix(in srgb, #fff 30%, transparent);
@supports (color: color-mix(in lab, red, red)) {
background-color: color-mix(in oklab, var(--color-white) 30%, transparent);
}
}
.bg-yellow-600 { .bg-yellow-600 {
background-color: var(--color-yellow-600); background-color: var(--color-yellow-600);
} }
@@ -1936,6 +1935,9 @@
.p-3 { .p-3 {
padding: calc(var(--spacing) * 3); padding: calc(var(--spacing) * 3);
} }
.p-4 {
padding: calc(var(--spacing) * 4);
}
.p-6 { .p-6 {
padding: calc(var(--spacing) * 6); padding: calc(var(--spacing) * 6);
} }
@@ -1975,9 +1977,6 @@
.py-\[0\.2rem\] { .py-\[0\.2rem\] {
padding-block: 0.2rem; padding-block: 0.2rem;
} }
.pt-2 {
padding-top: calc(var(--spacing) * 2);
}
.pr-8 { .pr-8 {
padding-right: calc(var(--spacing) * 8); padding-right: calc(var(--spacing) * 8);
} }
@@ -2041,6 +2040,10 @@
font-size: var(--text-base); font-size: var(--text-base);
line-height: var(--tw-leading, var(--text-base--line-height)); line-height: var(--tw-leading, var(--text-base--line-height));
} }
.text-lg {
font-size: var(--text-lg);
line-height: var(--tw-leading, var(--text-lg--line-height));
}
.text-sm { .text-sm {
font-size: var(--text-sm); font-size: var(--text-sm);
line-height: var(--tw-leading, var(--text-sm--line-height)); line-height: var(--tw-leading, var(--text-sm--line-height));
@@ -2154,12 +2157,18 @@
.text-gray-400 { .text-gray-400 {
color: var(--color-gray-400); color: var(--color-gray-400);
} }
.text-gray-600 {
color: var(--color-gray-600);
}
.text-gray-950 { .text-gray-950 {
color: var(--color-gray-950); color: var(--color-gray-950);
} }
.text-white { .text-white {
color: var(--color-white); color: var(--color-white);
} }
.text-zinc-100 {
color: var(--color-zinc-100);
}
.text-zinc-950 { .text-zinc-950 {
color: var(--color-zinc-950); color: var(--color-zinc-950);
} }
@@ -2450,10 +2459,6 @@
--tw-duration: 300ms; --tw-duration: 300ms;
transition-duration: 300ms; transition-duration: 300ms;
} }
.duration-500 {
--tw-duration: 500ms;
transition-duration: 500ms;
}
.ease-in { .ease-in {
--tw-ease: var(--ease-in); --tw-ease: var(--ease-in);
transition-timing-function: var(--ease-in); transition-timing-function: var(--ease-in);
@@ -2819,15 +2824,13 @@
line-height: var(--tw-leading, var(--text-sm--line-height)); line-height: var(--tw-leading, var(--text-sm--line-height));
} }
} }
.dark\:border-gray-700 { .dark\:bg-black\/30 {
&:where(.dark, .dark *) { &:where(.dark, .dark *) {
border-color: var(--color-gray-700); background-color: color-mix(in srgb, #000 30%, transparent);
@supports (color: color-mix(in lab, red, red)) {
background-color: color-mix(in oklab, var(--color-black) 30%, transparent);
} }
} }
.dark\:bg-gray-700 {
&:where(.dark, .dark *) {
background-color: var(--color-gray-700);
}
} }
.dark\:bg-slate-800 { .dark\:bg-slate-800 {
&:where(.dark, .dark *) { &:where(.dark, .dark *) {
@@ -2854,6 +2857,20 @@
color: var(--color-white); color: var(--color-white);
} }
} }
.dark\:text-zinc-800 {
&:where(.dark, .dark *) {
color: var(--color-zinc-800);
}
}
.dark\:hover\:bg-slate-600 {
&:where(.dark, .dark *) {
&:hover {
@media (hover: hover) {
background-color: var(--color-slate-600);
}
}
}
}
.\[\&_svg\]\:pointer-events-none { .\[\&_svg\]\:pointer-events-none {
& svg { & svg {
pointer-events: none; pointer-events: none;
@@ -2910,6 +2927,7 @@
} }
@layer components { @layer components {
.msg { .msg {
margin-bottom: calc(var(--spacing) * 5);
max-width: 75%; max-width: 75%;
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
padding-inline: calc(var(--spacing) * 3); padding-inline: calc(var(--spacing) * 3);
@@ -2932,23 +2950,19 @@
background-color: var(--color-zinc-800); background-color: var(--color-zinc-800);
} }
} }
.primary-button {
border-radius: var(--radius-lg);
background-color: var(--color-blue-300);
padding: calc(var(--spacing) * 3);
&:where(.dark, .dark *) {
background-color: var(--color-gray-800);
}
}
} }
body { body {
background-color: transparent !important; background-color: transparent !important;
margin: 0; margin: 0;
} }
.dark-input {
padding: 12px 20px;
margin: 8px 0;
background-color: #1e1e1e;
color: #ffffff;
border: 1px solid #333333;
border-radius: 8px;
font-family: "Inter", sans-serif;
font-size: 16px;
transition: all 0.3s ease;
outline: none;
}
@keyframes slideIn { @keyframes slideIn {
from { from {
opacity: 0; opacity: 0;