Compare commits
10 Commits
e63fd76d2f
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| dc85276567 | |||
| b7f9ac043d | |||
| a91949a2fd | |||
| 6364fdf1cd | |||
| edc425e28f | |||
| cafec90019 | |||
| d88501a872 | |||
| 2717dde5af | |||
| 9920bfcdee | |||
| 3ce2fa3841 |
12
crates/daemon/migrations/20260222_1_init.sql
Normal file
12
crates/daemon/migrations/20260222_1_init.sql
Normal 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);
|
||||||
@@ -1,21 +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;
|
||||||
|
|
||||||
pub struct ChatMessage {
|
#[derive(Debug, sqlx::FromRow)]
|
||||||
|
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<()>;
|
async fn save_message(
|
||||||
async fn get_all_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 {
|
||||||
@@ -39,15 +47,10 @@ impl SqliteChatRepository {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::migrate!("./migrations")
|
||||||
"CREATE TABLE IF NOT EXISTS message (
|
.run(&pool)
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
.await
|
||||||
text TEXT NOT NULL,
|
.inspect_err(|e| eprintln!("Migration failed! {}", e))?;
|
||||||
is_user BOOL NOT NULL
|
|
||||||
)",
|
|
||||||
)
|
|
||||||
.execute(&pool)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(Self { pool })
|
Ok(Self { pool })
|
||||||
}
|
}
|
||||||
@@ -55,29 +58,76 @@ 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<()> {
|
async fn save_message(
|
||||||
sqlx::query("INSERT INTO messages (text, is_user) values (?, ?)")
|
&self,
|
||||||
.bind(text)
|
text: &str,
|
||||||
.bind(is_user)
|
is_user: &bool,
|
||||||
.execute(&self.pool)
|
chat_id: &i64,
|
||||||
.await?;
|
) -> Result<ChatMessageData> {
|
||||||
Ok(())
|
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)
|
||||||
|
.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>> {
|
async fn get_latest_messages(
|
||||||
let rows = sqlx::query("SELECT id, text, is_user FROM messages ORDER BY id DESC LIMIT 10")
|
&self,
|
||||||
.fetch_all(&self.pool)
|
chat_id: &i64,
|
||||||
.await?;
|
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
|
||||||
|
.inspect_err(|e| println!("sql error: {}", e))?;
|
||||||
|
|
||||||
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())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
148
crates/daemon/src/daemongrpc.rs
Normal file
148
crates/daemon/src/daemongrpc.rs
Normal 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,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,113 +1,30 @@
|
|||||||
mod chatpersistence;
|
mod chatpersistence;
|
||||||
|
mod daemongrpc;
|
||||||
|
|
||||||
use std::cell::Cell;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::AtomicI64;
|
|
||||||
|
|
||||||
use genai::chat::{ChatMessage, ChatRequest};
|
|
||||||
use genai::Client;
|
use genai::Client;
|
||||||
use shared::ai::ai_daemon_server::{AiDaemon, AiDaemonServer};
|
use shared::ai::ai_service_server::AiServiceServer;
|
||||||
use shared::ai::{
|
use tonic::transport::Server;
|
||||||
ChatHistoryRequest, ChatHistoryResponse, ChatMessage as CMessage, ChatRequest as CRequest,
|
|
||||||
ChatResponse as CResponse, PromptRequest, PromptResponse,
|
|
||||||
};
|
|
||||||
use tonic::{transport::Server, Request, Response, Status};
|
|
||||||
|
|
||||||
use chatpersistence::SqliteChatRepository;
|
use chatpersistence::SqliteChatRepository;
|
||||||
|
use daemongrpc::DaemonServer;
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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::default();
|
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?;
|
||||||
|
|||||||
@@ -4,4 +4,4 @@ version = "0.1.0"
|
|||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
serde = "1.0.228"
|
serde = { version = "1.0.228", features = ["derive"] }
|
||||||
|
|||||||
@@ -13,4 +13,37 @@ 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 {
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||||
|
pub struct DaemonState {
|
||||||
|
pub is_ok: bool,
|
||||||
|
pub message: Option<String>,
|
||||||
|
pub error: Option<String>,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
package ai_daemon;
|
package ai_daemon;
|
||||||
|
|
||||||
service AiDaemon {
|
service AiService {
|
||||||
rpc Prompt(PromptRequest) returns (PromptResponse);
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -30,13 +31,13 @@ message ChatHistoryRequest {
|
|||||||
|
|
||||||
message ChatHistoryResponse {
|
message ChatHistoryResponse {
|
||||||
int64 chat_id = 1;
|
int64 chat_id = 1;
|
||||||
repeated ChatResponse history = 10;
|
repeated ChatMessage history = 10;
|
||||||
}
|
}
|
||||||
|
|
||||||
message PromptRequest {
|
message DaemonStatusRequest {}
|
||||||
string prompt = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message PromptResponse {
|
message DaemonStatusResponse {
|
||||||
string response = 1;
|
bool is_ok = 1;
|
||||||
|
optional string message = 10;
|
||||||
|
optional string error = 20;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|||||||
150
frontend/src-tauri/src/commands.rs
Normal file
150
frontend/src-tauri/src/commands.rs
Normal 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)
|
||||||
|
}
|
||||||
@@ -1,127 +1,43 @@
|
|||||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||||
|
|
||||||
use feshared::chatmessage::{Message, MessageHistory};
|
mod commands;
|
||||||
use shared::ai::{ai_daemon_client::AiDaemonClient, ChatRequest, PromptRequest};
|
|
||||||
use tauri::{Emitter, Manager, State};
|
|
||||||
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;
|
||||||
|
|
||||||
struct AppState {
|
use commands::{chat, chat_history, daemon_state, set_chat_id, toggle_dark_mode, toggle_popup};
|
||||||
grpc_client: Mutex<AiDaemonClient<tonic::transport::Channel>>,
|
use shared::ai::ai_service_client::AiServiceClient;
|
||||||
current_chat: Mutex<Option<i64>>,
|
|
||||||
|
pub struct AppConfig {
|
||||||
|
dark_mode: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
pub struct AppState {
|
||||||
fn toggle_popup(app_handle: tauri::AppHandle) {
|
grpc_client: Mutex<AiServiceClient<tonic::transport::Channel>>,
|
||||||
match app_handle.get_webview_window("popup") {
|
config: Mutex<AppConfig>,
|
||||||
Some(window) => {
|
current_chat_id: Mutex<Option<i64>>,
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
let channel = tonic::transport::Channel::from_static("http://[::1]:50051")
|
let channel = tonic::transport::Channel::from_static("http://[::1]:50051").connect_lazy();
|
||||||
.connect()
|
let client = AiServiceClient::new(channel);
|
||||||
.await
|
|
||||||
.expect("Could not connect to daemon!");
|
|
||||||
|
|
||||||
let client = AiDaemonClient::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,
|
||||||
prompt_llm,
|
|
||||||
chat_history,
|
chat_history,
|
||||||
|
set_chat_id,
|
||||||
chat,
|
chat,
|
||||||
|
daemon_state,
|
||||||
|
toggle_dark_mode,
|
||||||
])
|
])
|
||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
/* Auto-hide popup when focus is lost
|
/* Auto-hide popup when focus is lost
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
use crate::bridge::invoke;
|
use std::time::Duration;
|
||||||
use crate::popup::Popup;
|
|
||||||
|
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},
|
||||||
path,
|
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]
|
#[component]
|
||||||
pub fn App() -> impl IntoView {
|
pub fn App() -> impl IntoView {
|
||||||
@@ -12,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>
|
||||||
}
|
}
|
||||||
@@ -23,22 +34,62 @@ 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;
|
||||||
});
|
|
||||||
};
|
|
||||||
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;
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
view! {
|
view! {
|
||||||
<main class="window-shell opaque-bg">
|
<ThemeProvider>
|
||||||
<h1>"AI Dashboard"</h1>
|
<DaemonProvider>
|
||||||
<button on:click=on_click>Test popup</button>
|
<div class="min-h-screen w-screen bg-white dark:bg-zinc-900 text-gray-950 dark:text-white">
|
||||||
<button on:click=prompt>Prompt!</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>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
125
frontend/src/components.rs
Normal 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>
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
mod app;
|
mod app;
|
||||||
mod bridge;
|
mod bridge;
|
||||||
|
mod components;
|
||||||
mod popup;
|
mod popup;
|
||||||
|
|
||||||
use app::*;
|
use app::*;
|
||||||
|
|||||||
@@ -1,27 +1,45 @@
|
|||||||
use crate::bridge::invoke;
|
use crate::{
|
||||||
use feshared::chatmessage::{Message, MessageHistory};
|
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 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>| {
|
||||||
init_history.dispatch(());
|
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 |_| {
|
Effect::new(move |_| {
|
||||||
if let Some(mut dat) = init_history.value().get() {
|
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
|
// 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
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -68,36 +97,61 @@ 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! {
|
||||||
<main class="window-shell rounded-container">
|
<ConfirmDialog
|
||||||
<input
|
is_open=show_new_chat_confirm
|
||||||
class="dark-input"
|
on_confirm=Callback::new(new_chat)
|
||||||
type="text"
|
on_cancel=Callback::new(move |_| set_new_chat_confirm.set(false))
|
||||||
node_ref=prompt_input_ref
|
title="Open a new chat?".to_string()
|
||||||
placeholder="Prompt..."
|
message="Current chat is stored".to_string() />
|
||||||
autofocus
|
<div class="flex flex-col rounded-lg bg-white dark:bg-zinc-900 text-zinc-950 dark:text-white h-screen w-full">
|
||||||
on:input=move |ev| set_prompt_text.set(event_target_value(&ev))
|
<header class="relative p-3">
|
||||||
on:keydown=move |ev| {
|
<input
|
||||||
if ev.key() == "Enter" {
|
class="w-full p-3 rounded-lg bg-zinc-200 dark:bg-zinc-950"
|
||||||
prompt_action.dispatch(prompt_text.get());
|
type="text"
|
||||||
set_prompt_text.update(|s| *s = "".to_string());
|
node_ref=prompt_input_ref
|
||||||
|
placeholder="Prompt..."
|
||||||
|
autofocus
|
||||||
|
on:input=move |ev| set_prompt_text.set(event_target_value(&ev))
|
||||||
|
on:keydown=move |ev| {
|
||||||
|
if ev.key() == "Enter" {
|
||||||
|
prompt_action.dispatch(prompt_text.get());
|
||||||
|
set_prompt_text.update(|s| *s = "".to_string());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
prop:value=prompt_text
|
||||||
prop:value=prompt_text
|
/>
|
||||||
/>
|
<button class="absolute py-1 px-2 right-5 mt-2
|
||||||
<div class="response-area">
|
rounded-full
|
||||||
<For each=move || messages.get()
|
dark:bg-slate-800
|
||||||
key=|msg| msg.id
|
dark:hover:bg-slate-600"
|
||||||
let(msg)
|
on:click=move |_| set_new_chat_confirm.set(true)>+</button>
|
||||||
>
|
</header>
|
||||||
<div class=if msg.is_user {"msg msg-user"} else {"msg msg-model"}>{msg.text}</div>
|
<main class="flex-grow overflow-y-auto p-4">
|
||||||
</For>
|
<div class="flex flex-col">
|
||||||
</div>
|
<For each=move || messages.get()
|
||||||
</main>
|
key=|msg| msg.id
|
||||||
|
let(msg)
|
||||||
|
>
|
||||||
|
<div class=if msg.is_user {"msg msg-user"} else {"msg msg-model"}>{msg.text}</div>
|
||||||
|
</For>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<div class="fixed bottom-0 right-0 p-2"><DarkModeToggle /></div>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
37
frontend/styles-input.css
Normal file
37
frontend/styles-input.css
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
3449
frontend/styles.css
3449
frontend/styles.css
File diff suppressed because it is too large
Load Diff
10
frontend/tailwind.config.js
Normal file
10
frontend/tailwind.config.js
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
module.exports = {
|
||||||
|
darkMode: "selector",
|
||||||
|
content: ["./src/**/*.rs", "./index.html"],
|
||||||
|
theme: {
|
||||||
|
fontFamily: {
|
||||||
|
sans: ["Inter", "serif"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user