Compare commits
5 Commits
cafec90019
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| dc85276567 | |||
| b7f9ac043d | |||
| a91949a2fd | |||
| 6364fdf1cd | |||
| edc425e28f |
@@ -1,5 +0,0 @@
|
|||||||
CREATE TABLE IF NOT EXISTS messages (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
text TEXT NOT NULL,
|
|
||||||
is_user BOOL NOT NULL
|
|
||||||
);
|
|
||||||
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,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())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
@@ -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?;
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,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)
|
||||||
@@ -66,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()
|
||||||
|
|||||||
@@ -6,32 +6,35 @@ 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_dark_mode, 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 {
|
pub struct AppConfig {
|
||||||
dark_mode: bool,
|
dark_mode: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
grpc_client: Mutex<AiDaemonClient<tonic::transport::Channel>>,
|
grpc_client: Mutex<AiServiceClient<tonic::transport::Channel>>,
|
||||||
config: Mutex<AppConfig>,
|
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),
|
||||||
config: Mutex::new(AppConfig { dark_mode: true }),
|
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,
|
toggle_dark_mode,
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use feshared::daemon::DaemonState;
|
use feshared::{chatmessage::TauriCommand, daemon::DaemonState};
|
||||||
use leptos::logging::log;
|
|
||||||
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 serde::{Deserialize, Serialize};
|
use wasm_bindgen::JsValue;
|
||||||
use wasm_bindgen::{prelude::Closure, JsValue};
|
|
||||||
|
|
||||||
use crate::bridge::{invoke, listen};
|
|
||||||
use crate::popup::PopupView;
|
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";
|
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";
|
||||||
|
|
||||||
@@ -32,13 +34,7 @@ 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 toggle_dark_mode = |_ev: leptos::ev::MouseEvent| {
|
|
||||||
spawn_local(async {
|
|
||||||
let _ = invoke("toggle_dark_mode", JsValue::UNDEFINED).await;
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
view! {
|
view! {
|
||||||
@@ -46,7 +42,6 @@ fn Dashboard() -> impl IntoView {
|
|||||||
<DaemonProvider>
|
<DaemonProvider>
|
||||||
<div class="min-h-screen w-screen bg-white dark:bg-zinc-900 text-gray-950 dark:text-white">
|
<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>
|
<button class=BTN_PRIMARY on:click=on_click>Open chat</button>
|
||||||
<button class=BTN_PRIMARY on:click=toggle_dark_mode>asdf?</button>
|
|
||||||
</div>
|
</div>
|
||||||
</DaemonProvider>
|
</DaemonProvider>
|
||||||
<div class="fixed bottom-0 right-0 p-2">
|
<div class="fixed bottom-0 right-0 p-2">
|
||||||
@@ -56,22 +51,6 @@ fn Dashboard() -> impl IntoView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn DarkModeToggle() -> impl IntoView {
|
|
||||||
let toggle_dark_mode = |_ev: leptos::ev::MouseEvent| {
|
|
||||||
spawn_local(async {
|
|
||||||
let _ = invoke("toggle_dark_mode", 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]
|
#[component]
|
||||||
pub fn DaemonStatusIndicator() -> impl IntoView {
|
pub fn DaemonStatusIndicator() -> impl IntoView {
|
||||||
let (poll_count, set_pool_count) = signal(0);
|
let (poll_count, set_pool_count) = signal(0);
|
||||||
@@ -81,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
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -115,82 +93,3 @@ pub fn DaemonStatusIndicator() -> impl IntoView {
|
|||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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 val = invoke("daemon_state", JsValue::NULL).await;
|
|
||||||
let s: DaemonState = serde_wasm_bindgen::from_value(val).unwrap();
|
|
||||||
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]
|
|
||||||
fn DaemonErrorStatus(error: Option<String>) -> impl IntoView {
|
|
||||||
view! {
|
|
||||||
<ThemeProvider>
|
|
||||||
<div class="w-screen h-screen bg-white dark:bg-zinc-900">
|
|
||||||
<p>{ error.unwrap_or("Daemon error!".to_string()) } </p>
|
|
||||||
</div>
|
|
||||||
</ThemeProvider>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize, Serialize, Clone)]
|
|
||||||
struct DarkMode {
|
|
||||||
is_dark_mode: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[component]
|
|
||||||
pub fn ThemeProvider(children: Children) -> impl IntoView {
|
|
||||||
let (is_dark, set_dark) = signal(false);
|
|
||||||
|
|
||||||
Effect::new(move |_| {
|
|
||||||
spawn_local(async move {
|
|
||||||
let handler = Closure::wrap(Box::new(move |evt: JsValue| {
|
|
||||||
log!("Received!!!");
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct TauriEvent<T> {
|
|
||||||
payload: T,
|
|
||||||
}
|
|
||||||
if let Ok(wrapper) = serde_wasm_bindgen::from_value::<TauriEvent<DarkMode>>(evt) {
|
|
||||||
set_dark.set(wrapper.payload.is_dark_mode);
|
|
||||||
}
|
|
||||||
}) as Box<dyn FnMut(JsValue)>);
|
|
||||||
let unlisten = listen("dark-mode-changed", &handler).await;
|
|
||||||
// TODO use on_cleanup to call the unlisten JS function.
|
|
||||||
handler.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()}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,9 +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"])]
|
#[wasm_bindgen(js_namespace = ["window", "__TAURI__", "event"])]
|
||||||
pub async fn listen(event: &str, handler: &Closure<dyn FnMut(JsValue)>) -> JsValue;
|
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,9 +1,9 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
app::{DaemonProvider, DarkModeToggle, ThemeProvider},
|
bridge::{invoke_js, invoke_typed},
|
||||||
bridge::invoke,
|
components::{ConfirmDialog, DaemonProvider, DarkModeToggle, ThemeProvider},
|
||||||
};
|
};
|
||||||
use feshared::{
|
use feshared::{
|
||||||
chatmessage::{Message, MessageHistory},
|
chatmessage::{Message, MessageHistory, TauriCommand},
|
||||||
daemon::DaemonState,
|
daemon::DaemonState,
|
||||||
};
|
};
|
||||||
use leptos::{ev::keydown, html::Input, prelude::*};
|
use leptos::{ev::keydown, html::Input, prelude::*};
|
||||||
@@ -30,12 +30,8 @@ pub fn Popup() -> impl IntoView {
|
|||||||
use_context::<LocalResource<DaemonState>>().expect("No daemon connection context!");
|
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 |prev_status: Option<bool>| {
|
Effect::new(move |prev_status: Option<bool>| {
|
||||||
@@ -51,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
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -90,14 +97,29 @@ 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! {
|
||||||
|
<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">
|
<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="p-3">
|
<header class="relative p-3">
|
||||||
<input
|
<input
|
||||||
class="w-full p-3 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"
|
||||||
@@ -113,8 +135,13 @@ pub fn Popup() -> impl IntoView {
|
|||||||
}
|
}
|
||||||
prop:value=prompt_text
|
prop:value=prompt_text
|
||||||
/>
|
/>
|
||||||
|
<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>
|
</header>
|
||||||
<main class="flex-grow overflow-y-auto p-2">
|
<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
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -579,18 +579,21 @@
|
|||||||
.sticky {
|
.sticky {
|
||||||
position: sticky;
|
position: sticky;
|
||||||
}
|
}
|
||||||
|
.inset-0 {
|
||||||
|
inset: calc(var(--spacing) * 0);
|
||||||
|
}
|
||||||
.right-0 {
|
.right-0 {
|
||||||
right: calc(var(--spacing) * 0);
|
right: calc(var(--spacing) * 0);
|
||||||
}
|
}
|
||||||
.right-2 {
|
.right-2 {
|
||||||
right: calc(var(--spacing) * 2);
|
right: calc(var(--spacing) * 2);
|
||||||
}
|
}
|
||||||
|
.right-5 {
|
||||||
|
right: calc(var(--spacing) * 5);
|
||||||
|
}
|
||||||
.bottom-0 {
|
.bottom-0 {
|
||||||
bottom: calc(var(--spacing) * 0);
|
bottom: calc(var(--spacing) * 0);
|
||||||
}
|
}
|
||||||
.bottom-4 {
|
|
||||||
bottom: calc(var(--spacing) * 4);
|
|
||||||
}
|
|
||||||
.isolate {
|
.isolate {
|
||||||
isolation: isolate;
|
isolation: isolate;
|
||||||
}
|
}
|
||||||
@@ -672,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);
|
||||||
}
|
}
|
||||||
@@ -687,9 +693,15 @@
|
|||||||
.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-2 {
|
||||||
|
margin-bottom: calc(var(--spacing) * 2);
|
||||||
|
}
|
||||||
.mb-8 {
|
.mb-8 {
|
||||||
margin-bottom: calc(var(--spacing) * 8);
|
margin-bottom: calc(var(--spacing) * 8);
|
||||||
}
|
}
|
||||||
@@ -771,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);
|
||||||
@@ -1281,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);
|
||||||
}
|
}
|
||||||
@@ -1578,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);
|
||||||
}
|
}
|
||||||
@@ -1924,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);
|
||||||
}
|
}
|
||||||
@@ -1963,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);
|
||||||
}
|
}
|
||||||
@@ -2029,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));
|
||||||
@@ -2151,6 +2166,9 @@
|
|||||||
.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);
|
||||||
}
|
}
|
||||||
@@ -2806,6 +2824,14 @@
|
|||||||
line-height: var(--tw-leading, var(--text-sm--line-height));
|
line-height: var(--tw-leading, var(--text-sm--line-height));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
.dark\:bg-black\/30 {
|
||||||
|
&:where(.dark, .dark *) {
|
||||||
|
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-slate-800 {
|
.dark\:bg-slate-800 {
|
||||||
&:where(.dark, .dark *) {
|
&:where(.dark, .dark *) {
|
||||||
background-color: var(--color-slate-800);
|
background-color: var(--color-slate-800);
|
||||||
@@ -2831,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;
|
||||||
@@ -2887,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);
|
||||||
@@ -2909,6 +2950,14 @@
|
|||||||
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;
|
||||||
|
|||||||
Reference in New Issue
Block a user