Compare commits

..

10 Commits

20 changed files with 4216 additions and 372 deletions

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,21 +1,29 @@
use anyhow::Result;
use directories::ProjectDirs;
use sqlx::sqlite::SqliteConnectOptions;
use sqlx::Row;
use sqlx::SqlitePool;
use sqlx::{Row, SqlitePool};
use tokio::fs;
use tonic::async_trait;
pub struct ChatMessage {
#[derive(Debug, sqlx::FromRow)]
pub struct ChatMessageData {
pub id: i64,
pub chat_id: i64,
pub text: String,
pub is_user: bool,
}
#[async_trait]
pub trait ChatRepository {
async fn save_message(&self, text: &str, is_user: &bool) -> Result<()>;
async fn get_all_messages(&self) -> Result<Vec<ChatMessage>>;
async fn save_message(
&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 {
@@ -39,15 +47,10 @@ impl SqliteChatRepository {
)
.await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS message (
id INTEGER PRIMARY KEY AUTOINCREMENT,
text TEXT NOT NULL,
is_user BOOL NOT NULL
)",
)
.execute(&pool)
.await?;
sqlx::migrate!("./migrations")
.run(&pool)
.await
.inspect_err(|e| eprintln!("Migration failed! {}", e))?;
Ok(Self { pool })
}
@@ -55,29 +58,76 @@ impl SqliteChatRepository {
#[async_trait]
impl ChatRepository for SqliteChatRepository {
async fn save_message(&self, text: &str, is_user: &bool) -> Result<()> {
sqlx::query("INSERT INTO messages (text, is_user) values (?, ?)")
async fn save_message(
&self,
text: &str,
is_user: &bool,
chat_id: &i64,
) -> Result<ChatMessageData> {
let result = sqlx::query_as::<_, ChatMessageData>(
r#"
INSERT INTO messages (text, is_user, chat_id)
VALUES (?, ?, ?)
RETURNING id, chat_id, text, is_user
"#,
)
.bind(text)
.bind(is_user)
.execute(&self.pool)
.await?;
Ok(())
.bind(chat_id)
.fetch_one(&self.pool)
.await
.inspect_err(|e| println!("sql error: {}", e))?;
Ok(result)
}
async fn get_all_messages(&self) -> Result<Vec<ChatMessage>> {
let rows = sqlx::query("SELECT id, text, is_user FROM messages ORDER BY id DESC LIMIT 10")
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(
format!(
r#"
SELECT * FROM (
SELECT id, chat_id, text, is_user
FROM messages
WHERE chat_id = {chat_id}
ORDER BY id DESC
LIMIT {count}
) AS subquery ORDER BY id ASC;"#
)
.as_str(),
)
.fetch_all(&self.pool)
.await?;
.await
.inspect_err(|e| println!("sql error: {}", e))?;
let messages = rows
.into_iter()
.map(|row| ChatMessage {
.map(|row| ChatMessageData {
id: row.get(0),
text: row.get(1),
is_user: row.get(2),
chat_id: row.get(1),
text: row.get(2),
is_user: row.get(3),
})
.collect();
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

@@ -0,0 +1,148 @@
use crate::chatpersistence::{ChatMessageData, ChatRepository};
use anyhow::Result;
use genai::chat::{ChatMessage, ChatRequest};
use genai::Client;
use shared::ai::ai_service_server::AiService;
use shared::ai::{
ChatHistoryRequest, ChatHistoryResponse, ChatMessage as CMessage, ChatRequest as CRequest,
ChatResponse as CResponse, DaemonStatusRequest, DaemonStatusResponse,
};
use std::sync::Arc;
use tonic::{Code, Request, Response, Status};
pub struct DaemonServer {
repo: Arc<dyn ChatRepository + Send + Sync>,
client: Client,
}
impl DaemonServer {
pub fn new(repo: Arc<dyn ChatRepository + Send + Sync>, client: Client) -> Self {
Self {
repo: repo,
client: client,
}
}
}
#[tonic::async_trait]
impl AiService for DaemonServer {
async fn chat(&self, request: Request<CRequest>) -> Result<Response<CResponse>, Status> {
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(
&self
.repo
.save_message(r.text(), &true, &chat_id)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?,
);
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(
&self
.repo
.save_message(response_text, &false, &chat_id)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?,
);
let response = CResponse {
chat_id: ai_message.chat_id,
messages: vec![user_message, ai_message],
};
return Ok(Response::new(response));
}
async fn chat_history(
&self,
request: Request<ChatHistoryRequest>,
) -> 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
.repo
.get_latest_messages(&chat_id, &20)
.await
.map_err(|e| Status::new(Code::Internal, e.to_string()))?;
let response = ChatHistoryResponse {
chat_id: chat_id,
history: messages.iter().map(|m| message_to_dto(m)).collect(),
};
Ok(Response::new(response))
}
async fn daemon_status(
&self,
_: Request<DaemonStatusRequest>,
) -> Result<Response<DaemonStatusResponse>, Status> {
let status = DaemonStatusResponse {
is_ok: true,
message: None,
error: None,
};
Ok(Response::new(status))
}
}
pub fn message_to_dto(msg: &ChatMessageData) -> CMessage {
CMessage {
id: msg.id,
chat_id: msg.chat_id,
text: msg.text.clone(),
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

@@ -1,113 +1,30 @@
mod chatpersistence;
mod daemongrpc;
use std::cell::Cell;
use std::sync::atomic::AtomicI64;
use std::sync::Arc;
use genai::chat::{ChatMessage, ChatRequest};
use genai::Client;
use shared::ai::ai_daemon_server::{AiDaemon, AiDaemonServer};
use shared::ai::{
ChatHistoryRequest, ChatHistoryResponse, ChatMessage as CMessage, ChatRequest as CRequest,
ChatResponse as CResponse, PromptRequest, PromptResponse,
};
use tonic::{transport::Server, Request, Response, Status};
use shared::ai::ai_service_server::AiServiceServer;
use tonic::transport::Server;
use chatpersistence::SqliteChatRepository;
pub struct DaemonServer {
message_counter: AtomicI64,
}
impl Default for DaemonServer {
fn default() -> Self {
Self {
message_counter: AtomicI64::new(0),
}
}
}
#[tonic::async_trait]
impl AiDaemon for DaemonServer {
async fn prompt(
&self,
request: Request<PromptRequest>,
) -> Result<Response<PromptResponse>, Status> {
let remote_a = request.remote_addr();
let prompt_value = request.into_inner().prompt;
println!("Request from {:?}: {:?}", remote_a, prompt_value);
let client = Client::default();
let response = prompt_ollama(&client, "llama3.2", prompt_value.as_str())
.await
.unwrap_or_else(|err| format!("Prompt error: {}", err));
println!("Respone: {}", response);
let reply = PromptResponse { response: response };
Ok(Response::new(reply))
}
async fn chat(&self, request: Request<CRequest>) -> Result<Response<CResponse>, Status> {
let r = request.into_inner();
println!("<<<: {}", r.text());
let response = CResponse {
chat_id: 1,
messages: vec![
CMessage {
id: self
.message_counter
.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
text: r.text().to_string(),
is_user: true,
},
CMessage {
id: self
.message_counter
.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
text: format!("Pong: {}", r.text()),
is_user: false,
},
],
};
return Ok(Response::new(response));
}
async fn chat_history(
&self,
request: Request<ChatHistoryRequest>,
) -> Result<Response<ChatHistoryResponse>, Status> {
let response = ChatHistoryResponse {
chat_id: 1,
history: vec![],
};
Ok(Response::new(response))
}
}
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)
}
use daemongrpc::DaemonServer;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let chat_repo = SqliteChatRepository::new().await?;
let client = Client::default();
let addr_s = "[::1]:50051";
let addr = addr_s.parse().unwrap();
let daemon = DaemonServer::default();
let daemon = DaemonServer::new(Arc::new(chat_repo), client);
let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(shared::ai::FILE_DESCRIPTOR_SET)
.build_v1()?;
println!("Started daemon at {}", addr_s);
Server::builder()
.add_service(AiDaemonServer::new(daemon))
.add_service(AiServiceServer::new(daemon))
.add_service(reflection_service)
.serve(addr)
.await?;

View File

@@ -4,4 +4,4 @@ version = "0.1.0"
edition = "2021"
[dependencies]
serde = "1.0.228"
serde = { version = "1.0.228", features = ["derive"] }

View File

@@ -13,4 +13,37 @@ pub mod chatmessage {
pub chat_id: Option<i64>,
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 {
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DaemonState {
pub is_ok: bool,
pub message: Option<String>,
pub error: Option<String>,
}
}

View File

@@ -1,14 +1,15 @@
syntax = "proto3";
package ai_daemon;
service AiDaemon {
rpc Prompt(PromptRequest) returns (PromptResponse);
service AiService {
rpc Chat(ChatRequest) returns (ChatResponse);
rpc ChatHistory(ChatHistoryRequest) returns (ChatHistoryResponse);
rpc DaemonStatus(DaemonStatusRequest) returns (DaemonStatusResponse);
}
message ChatMessage {
int64 id = 1;
int64 chat_id = 2;
string text = 10;
bool is_user = 20;
}
@@ -30,13 +31,13 @@ message ChatHistoryRequest {
message ChatHistoryResponse {
int64 chat_id = 1;
repeated ChatResponse history = 10;
repeated ChatMessage history = 10;
}
message PromptRequest {
string prompt = 1;
}
message DaemonStatusRequest {}
message PromptResponse {
string response = 1;
message DaemonStatusResponse {
bool is_ok = 1;
optional string message = 10;
optional string error = 20;
}

View File

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

View File

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

View File

@@ -0,0 +1,150 @@
use serde::Serialize;
use tauri::{Emitter, Manager, State};
use feshared::{
chatmessage::{Message, MessageHistory},
daemon::DaemonState,
};
use shared::ai::{ChatHistoryRequest, ChatRequest, DaemonStatusRequest};
use crate::AppState;
#[tauri::command]
pub fn toggle_popup(app_handle: tauri::AppHandle) {
match app_handle.get_webview_window("popup") {
Some(window) => {
let is_visible = window.is_visible().unwrap_or(false);
if is_visible {
window.hide().unwrap();
} else {
window.show().unwrap();
window.set_focus().unwrap();
let _ = window.emit("window-focused", ());
}
}
None => {
println!("ERROR: Window with label 'popup' not found!");
}
}
}
#[tauri::command]
pub async fn chat(state: State<'_, AppState>, prompt: String) -> Result<Vec<Message>, String> {
let mut client = state.grpc_client.lock().await;
let cid = state.current_chat_id.lock().await.clone();
let request = tonic::Request::new(ChatRequest {
chat_id: cid,
text: Some(prompt),
});
match client.chat(request).await {
Ok(response) => {
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| {
if m.is_user {
println!(">>> {}", m.text)
} else {
println!("<<< {}", m.text)
}
});
Ok(r.messages
.iter()
.map(|msg| Message {
id: msg.id,
text: msg.text.clone(),
is_user: msg.is_user,
})
.collect())
}
Err(e) => {
println!("gRPC error: {}", e);
Err(format!("gRPC error: {}", e))
}
}
}
#[tauri::command]
pub async fn set_chat_id(
state: State<'_, AppState>,
chat_id: Option<i64>,
) -> 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 chat_id = state.current_chat_id.lock().await.clone();
let result = client
.chat_history(ChatHistoryRequest { chat_id: chat_id })
.await;
match result {
Ok(response) => {
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 {
chat_id: Some(r.chat_id),
history: r
.history
.iter()
.map(|m| Message {
id: m.id,
is_user: m.is_user,
text: m.text.clone(),
})
.collect(),
})
}
Err(e) => Err(format!("gRPC error: {e}")),
}
}
#[tauri::command]
pub async fn daemon_state(state: State<'_, AppState>) -> Result<DaemonState, String> {
let mut client = state.grpc_client.lock().await;
let result = client.daemon_status(DaemonStatusRequest {}).await;
match result {
Ok(status) => {
let status_inner = status.into_inner();
Ok(DaemonState {
is_ok: status_inner.is_ok,
message: Some(status_inner.message.unwrap_or(String::from("Daemon OK"))),
error: status_inner.error,
})
}
Err(e) => Ok(DaemonState {
is_ok: false,
message: None,
error: Some(e.message().to_string()),
}),
}
}
#[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

@@ -1,127 +1,43 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use feshared::chatmessage::{Message, MessageHistory};
use shared::ai::{ai_daemon_client::AiDaemonClient, ChatRequest, PromptRequest};
use tauri::{Emitter, Manager, State};
mod commands;
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut, ShortcutState};
use tokio::sync::Mutex;
struct AppState {
grpc_client: Mutex<AiDaemonClient<tonic::transport::Channel>>,
current_chat: Mutex<Option<i64>>,
use commands::{chat, chat_history, daemon_state, set_chat_id, toggle_dark_mode, toggle_popup};
use shared::ai::ai_service_client::AiServiceClient;
pub struct AppConfig {
dark_mode: bool,
}
#[tauri::command]
fn toggle_popup(app_handle: tauri::AppHandle) {
match app_handle.get_webview_window("popup") {
Some(window) => {
let is_visible = window.is_visible().unwrap_or(false);
if is_visible {
window.hide().unwrap();
} else {
window.show().unwrap();
window.set_focus().unwrap();
let _ = window.emit("window-focused", ());
}
}
None => {
println!("ERROR: Window with label 'popup' not found!");
}
}
}
#[tauri::command]
async fn prompt_llm(state: State<'_, AppState>, prompt: String) -> Result<String, String> {
println!(">>>> {}", prompt);
let mut client = state.grpc_client.lock().await;
let request = tonic::Request::new(PromptRequest { prompt });
match client.prompt(request).await {
Ok(response) => Ok(response.into_inner().response),
Err(e) => Err(format!("gRPC error: {}", e)),
}
}
#[tauri::command]
async fn chat(
state: State<'_, AppState>,
prompt: String,
chat_id: Option<i64>,
) -> Result<Vec<Message>, String> {
let mut client = state.grpc_client.lock().await;
let request = tonic::Request::new(ChatRequest {
chat_id: chat_id,
text: Some(prompt),
});
match client.chat(request).await {
Ok(response) => {
let r = response.into_inner();
r.messages.iter().for_each(|m| {
if m.is_user {
println!(">>> {}", m.text)
} else {
println!("<<< {}", m.text)
}
});
Ok(r.messages
.iter()
.map(|msg| Message {
id: msg.id,
text: msg.text.clone(),
is_user: msg.is_user,
})
.collect())
}
Err(e) => Err(format!("gRPC error: {}", e)),
}
}
#[tauri::command]
async fn chat_history(
state: State<'_, AppState>,
chat_id: Option<i64>,
) -> Result<MessageHistory, String> {
let history = MessageHistory {
chat_id: match chat_id {
Some(_) => chat_id,
None => Some(-1),
},
history: vec![
Message {
id: 1,
text: String::from("asd"),
is_user: false,
},
Message {
id: 2,
text: String::from("yeah!!!!"),
is_user: true,
},
],
};
Ok(history)
pub struct AppState {
grpc_client: Mutex<AiServiceClient<tonic::transport::Channel>>,
config: Mutex<AppConfig>,
current_chat_id: Mutex<Option<i64>>,
}
#[tokio::main]
async fn main() {
let channel = tonic::transport::Channel::from_static("http://[::1]:50051")
.connect()
.await
.expect("Could not connect to daemon!");
let client = AiDaemonClient::new(channel);
let channel = tonic::transport::Channel::from_static("http://[::1]:50051").connect_lazy();
let client = AiServiceClient::new(channel);
tauri::Builder::default()
.manage(AppState {
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())
.invoke_handler(tauri::generate_handler![
toggle_popup,
prompt_llm,
chat_history,
set_chat_id,
chat,
daemon_state,
toggle_dark_mode,
])
.setup(|app| {
/* Auto-hide popup when focus is lost

View File

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

View File

@@ -1,10 +1,21 @@
use crate::bridge::invoke;
use crate::popup::Popup;
use std::time::Duration;
use feshared::{chatmessage::TauriCommand, daemon::DaemonState};
use leptos::{prelude::*, reactive::spawn_local};
use leptos_router::{
components::{Route, Router, Routes},
path,
};
use wasm_bindgen::JsValue;
use crate::popup::PopupView;
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";
#[component]
pub fn App() -> impl IntoView {
@@ -12,7 +23,7 @@ pub fn App() -> impl IntoView {
<Router>
<Routes fallback=|| view! { "Page not found."}>
<Route path=path!("/") view=Dashboard />
<Route path=path!("/popup") view=Popup />
<Route path=path!("/popup") view=PopupView />
</Routes>
</Router>
}
@@ -23,22 +34,62 @@ fn Dashboard() -> impl IntoView {
let on_click = move |_ev: leptos::ev::MouseEvent| {
spawn_local(async move {
let empty_args = serde_wasm_bindgen::to_value(&serde_json::json!({})).unwrap();
invoke("toggle_popup", empty_args).await;
});
};
let prompt = |_ev: leptos::ev::MouseEvent| {
spawn_local(async {
let prompt =
serde_wasm_bindgen::to_value(&serde_json::json!({"prompt": "jee juu juu"}))
.unwrap();
invoke("prompt_llm", prompt).await;
invoke_js(TauriCommand::TogglePopup, empty_args).await;
});
};
view! {
<main class="window-shell opaque-bg">
<h1>"AI Dashboard"</h1>
<button on:click=on_click>Test popup</button>
<button on:click=prompt>Prompt!</button>
</main>
<ThemeProvider>
<DaemonProvider>
<div class="min-h-screen w-screen bg-white dark:bg-zinc-900 text-gray-950 dark:text-white">
<button class=BTN_PRIMARY on:click=on_click>Open chat</button>
</div>
</DaemonProvider>
<div class="fixed bottom-0 right-0 p-2">
<DarkModeToggle />
</div>
</ThemeProvider>
}
}
#[component]
pub fn DaemonStatusIndicator() -> 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 = LocalResource::new(move || async move {
poll_count.get();
let s: DaemonState = invoke_typed(TauriCommand::DaemonState, JsValue::NULL).await;
s
});
let f = |state: Option<DaemonState>| {
let color = match state.clone() {
Some(s) => match s.is_ok {
true => "bg-green-600",
false => "bg-red-600",
},
None => "bg-yellow-600",
};
let text = match state {
Some(s) => match s.error {
Some(err) => err,
None => s.message.unwrap_or(String::from("")),
},
None => String::from("Loading..."),
};
view! {
<div class="flex">
<div class={format!("mt-1 h-4 w-4 rounded-full flex-none {color}")}></div>
<span class="ml-2 flex-none text-gray-400 dark:text-gray-600">{ text }</span>
</div>
}
};
view! {
<div>
{move || f(status.get())}
</div>
}
}

View File

@@ -1,6 +1,41 @@
use feshared::chatmessage::TauriCommand;
use serde::{de::DeserializeOwned, Deserialize};
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[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 bridge;
mod components;
mod popup;
use app::*;

View File

@@ -1,27 +1,45 @@
use crate::bridge::invoke;
use feshared::chatmessage::{Message, MessageHistory};
use crate::{
bridge::{invoke_js, invoke_typed},
components::{ConfirmDialog, DaemonProvider, DarkModeToggle, ThemeProvider},
};
use feshared::{
chatmessage::{Message, MessageHistory, TauriCommand},
daemon::DaemonState,
};
use leptos::{ev::keydown, html::Input, prelude::*};
use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use wasm_bindgen_futures::spawn_local;
#[component]
pub fn PopupView() -> impl IntoView {
view! {<ThemeProvider>
<DaemonProvider>
<Popup />
</DaemonProvider>
</ThemeProvider>
}
}
#[component]
pub fn Popup() -> impl IntoView {
// Prompt signals and and action
let prompt_input_ref = NodeRef::<Input>::new();
let (prompt_text, set_prompt_text) = signal(String::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 response = invoke(
"chat_history",
serde_wasm_bindgen::to_value(&serde_json::json!({"chat_id": 1})).unwrap(),
)
.await;
let history: MessageHistory = serde_wasm_bindgen::from_value(response).unwrap();
let history: MessageHistory =
invoke_typed(TauriCommand::ChatHistory, JsValue::UNDEFINED).await;
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(());
}
current_ok
});
Effect::new(move |_| {
if let Some(mut dat) = init_history.value().get() {
@@ -29,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
let prompt_action = Action::new_local(|prompt: &String| {
let prompt = prompt.clone();
async move {
let response = invoke(
"chat",
let result: Vec<Message> = invoke_typed(
TauriCommand::Chat,
serde_wasm_bindgen::to_value(&serde_json::json!({"prompt": prompt})).unwrap(),
)
.await;
let result: Vec<Message> = serde_wasm_bindgen::from_value(response).unwrap();
result
}
});
@@ -68,15 +97,31 @@ pub fn Popup() -> impl IntoView {
let _ = window_event_listener(keydown, move |ev| {
if ev.key() == "Escape" {
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! {
<main class="window-shell rounded-container">
<ConfirmDialog
is_open=show_new_chat_confirm
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
class="dark-input"
class="w-full p-3 rounded-lg bg-zinc-200 dark:bg-zinc-950"
type="text"
node_ref=prompt_input_ref
placeholder="Prompt..."
@@ -90,7 +135,14 @@ pub fn Popup() -> impl IntoView {
}
prop:value=prompt_text
/>
<div class="response-area">
<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">
<For each=move || messages.get()
key=|msg| msg.id
let(msg)
@@ -99,5 +151,7 @@ pub fn Popup() -> impl IntoView {
</For>
</div>
</main>
<div class="fixed bottom-0 right-0 p-2"><DarkModeToggle /></div>
</div>
}
}

37
frontend/styles-input.css Normal file
View File

@@ -0,0 +1,37 @@
@import "tailwindcss";
@custom-variant dark (&:where(.dark, .dark *));
@layer components {
.msg {
@apply rounded-lg mb-5 px-3 py-2 dark:bg-gray-800 max-w-[75%];
}
.msg-model {
@apply self-start bg-blue-200 dark:bg-slate-800;
}
.msg-user {
@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 {
background-color: transparent !important;
margin: 0;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(10px) scale(0.95);
}
to {
opacity: 1;
transform: translateY(0) scale(1);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: "selector",
content: ["./src/**/*.rs", "./index.html"],
theme: {
fontFamily: {
sans: ["Inter", "serif"],
},
},
};