Skip to content

Commit

Permalink
Merge pull request #65 from RibirX/refactor/app_split
Browse files Browse the repository at this point in the history
refactor: 💡 split AppGUI when compose widget
  • Loading branch information
sologeek authored Jan 22, 2024
2 parents 293ead6 + f9d931f commit 585fc69
Show file tree
Hide file tree
Showing 35 changed files with 765 additions and 945 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
on:
merge_group:
pull_request:
push:
branches:
- master

env:
CARGO_INCREMENTAL: false
CARGO_TERM_COLOR: always
RUST_BACKTRACE: full
RUSTDOCFLAGS: -Dwarnings

name: CI
jobs:
lint:
name: rust code lint
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v3
- uses: dtolnay/rust-toolchain@stable
with:
toolchain: nightly-2023-10-15
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- name: format style check
run: cargo fmt --all -- --check
- name: cargo clippy check
run: cargo clippy --all-targets --all-features -- -D warnings
- name: cargo check
run: cargo check
4 changes: 2 additions & 2 deletions cli/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,10 @@ pub fn msg_handler(args: ArgMatches, app_data: &mut AppData) -> ReplResult<Optio
}

let mut ret_msg = String::new();
let bot = app_data.info().def_bot();
let bot_id = app_data.info().def_bot().id().clone();
let runtime = tokio::runtime::Runtime::new().unwrap();
runtime.block_on(async {
if let Ok(mut stream) = create_text_request(bot, app_data.info())
if let Ok(mut stream) = create_text_request(app_data.info(), bot_id)
.request(content.expect("content is required").clone())
.await
{
Expand Down
1 change: 1 addition & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,6 @@ fn main() -> ReplResult<()> {
.about("Send message")]),
msg_handler,
);

repl.run()
}
8 changes: 1 addition & 7 deletions config/bot.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
{
"vars": {},
"providers": [
{
"name": "OpenAI",
"base_url": "https://api.ribir.org/stream/open_ai",
"token": "v1.eyJ1c2VyX2lkIjoxMDAxMTgsImV4cCI6MTcwNTQ2NDI4MSwidmVyIjoidjEifQ.-64yece5gSrdUwjY7sTnwoQ858kX-YyzRM7EuKCTI10"
}
],
"providers": [],
"bots": [
{
"id": "PoleStar Assistant",
Expand Down
4 changes: 1 addition & 3 deletions core/src/model/app_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ impl AppData {
pub fn new_channel(&mut self, name: String, desc: Option<String>, cfg: ChannelCfg) -> Uuid {
let channel_id = Uuid::new_v4();
let db = self.db.as_mut().map(|db| NonNull::from(&**db));
let info = &mut self.info;
let info = &self.info;
let app_info = Some(NonNull::from(&**info));
let channel = Channel::new(channel_id, name, desc, cfg, app_info, db);

Expand Down Expand Up @@ -373,7 +373,6 @@ impl AppData {
self.db = db;

let cur_channel_id = local_state.cur_channel_id();

let cur_channel = channels
.iter()
.find(|channel| Some(*channel.id()) == cur_channel_id.map(|id| id));
Expand All @@ -386,7 +385,6 @@ impl AppData {
};

self.info.as_mut().set_cur_channel_id(cur_channel_id);

let ptr = NonNull::from(&*self.info);
channels.iter_mut().for_each(|channel| {
channel.set_app_info(ptr);
Expand Down
2 changes: 1 addition & 1 deletion core/src/model/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub struct PartialBot {

impl PartialBot {
pub fn id(&self) -> &BotId { &self.id }

pub fn to_bot(self) -> Option<Bot> {
self.is_complete().then(|| Bot {
id: self.id,
Expand Down
2 changes: 1 addition & 1 deletion core/src/model/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use uuid::Uuid;

use crate::db::{executor::ActionPersist, pool::PersistenceDB};

use super::{msg::Msg, AppInfo, Bot, MsgAction, BotId};
use super::{msg::Msg, AppInfo, Bot, BotId, MsgAction};

pub type ChannelId = Uuid;

Expand Down
16 changes: 6 additions & 10 deletions core/src/model/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,10 @@ impl Msg {
cur_idx: 0,
cont_list,
meta,
created_at: created_at.map_or_else(
|| Utc::now(),
|t| {
let dt = NaiveDateTime::from_timestamp_millis(t).unwrap();
DateTime::from_naive_utc_and_offset(dt, Utc)
},
),
created_at: created_at.map_or_else(Utc::now, |t| {
let dt = NaiveDateTime::from_timestamp_millis(t).unwrap();
DateTime::from_naive_utc_and_offset(dt, Utc)
}),
}
}

Expand Down Expand Up @@ -156,10 +153,9 @@ impl Msg {
}

#[inline]
pub fn add_cont(&mut self, cont: MsgCont) {
let last_idx = self.cont_list.len();
pub fn add_cont(&mut self, cont: MsgCont) -> usize {
self.cont_list.push(cont);
self.cur_idx = last_idx as _;
self.cont_list.len() - 1
}

#[inline]
Expand Down
13 changes: 3 additions & 10 deletions core/src/model/user.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use derive_builder::Builder;
use serde::Deserialize;

use crate::service::req::request_quota;

use super::GLOBAL_VARS;

#[derive(Builder, Debug, Default, Clone)]
Expand Down Expand Up @@ -46,11 +44,6 @@ impl User {

#[inline]
pub fn uid(&self) -> u64 { self.uid }

pub fn set_quota(&mut self, quota: Option<Quota>) { self.quota = quota; }

#[inline]
pub fn quota(&self) -> Option<&Quota> { self.quota.as_ref() }
}

#[derive(Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -85,8 +78,8 @@ impl Quota {

#[derive(Deserialize, Debug)]
pub struct QuotaInfo {
user_id: u64,
limits: f32,
used: f32,
// user_id: u64,
// limits: f32,
// used: f32,
pub statistics: serde_json::Value,
}
13 changes: 7 additions & 6 deletions core/src/service/req.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use serde_json_path::JsonPath;
use crate::{
error::{PolestarError, PolestarResult},
model::{
AppInfo, Bot, FeedbackMessageListForServer, FeedbackTimestamp, GlbVar, Quota, ServerProvider,
UserFeedbackMessageForServer, GLOBAL_VARS,
AppInfo, Bot, BotId, FeedbackMessageListForServer, FeedbackTimestamp, GlbVar, Quota,
ServerProvider, UserFeedbackMessageForServer, GLOBAL_VARS,
},
};

Expand Down Expand Up @@ -52,11 +52,12 @@ async fn req_stream(
Ok(stream)
}

pub fn create_text_request<'a>(bot: &'a Bot, info: &'a AppInfo) -> TextStreamReq {
pub fn create_text_request(info: &AppInfo, bot_id: BotId) -> TextStreamReq {
let bot = info.bot(&bot_id).unwrap();
let sp_name = bot.sp();
let sp = info.providers().get(sp_name);
if let Some(sp) = sp {
create_req_from_bot(bot, Some(&sp))
create_req_from_bot(bot, Some(sp))
} else {
create_req_from_bot(bot, default_polestar_provider(sp_name, info).as_ref())
}
Expand Down Expand Up @@ -187,7 +188,7 @@ fn create_req_from_bot(bot: &Bot, sp: Option<&ServerProvider>) -> TextStreamReq
if let Some(base_url) = JsonPath::parse("$.sp.base_url")
.ok()
.and_then(|path| path.query(&env).exactly_one().ok())
.map(|val| to_value_str(val))
.map(to_value_str)
{
url = format!("{}{}", base_url, url);
}
Expand All @@ -206,7 +207,7 @@ fn replace_val(src: &str, path_rex: &Regex, env: &JsonValue) -> String {
val.push_str(&src[pos..rg.start]);
pos = rg.end;

if let Some(replaced) = JsonPath::parse(&cap[1].to_string())
if let Some(replaced) = JsonPath::parse(&cap[1])
.ok()
.and_then(|path| path.query(env).exactly_one().ok())
{
Expand Down
12 changes: 4 additions & 8 deletions core/src/utils/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,19 +134,15 @@ fn parse_user_bot_cfgs(user_data_path: PathBuf, file: &str) -> PolestarResult<Bo

for idx in remove_idx.into_iter().rev() {
let bot = user_partial_bots.remove(idx);
official_bots
.iter_mut()
.find(|b| b.id() == bot.id())
.map(|b| b.merge(&bot));
if let Some(b) = official_bots.iter_mut().find(|b| b.id() == bot.id()) {
b.merge(&bot);
}
}

user_bots.extend(user_partial_bots.into_iter().filter_map(|bot| bot.to_bot()));

Ok(BotCfg {
bots: official_bots
.into_iter()
.chain(user_bots.into_iter())
.collect(),
bots: official_bots.into_iter().chain(user_bots).collect(),
providers: user_sp,
})
}
Expand Down
4 changes: 2 additions & 2 deletions gui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ description.workspace = true

[dependencies]
polestar-core = { path = "../core", features = ["persistence"] }
ribir = { path = "../../Ribir/ribir", features = ["png", "tokio-async"] }
ribir_algo = { path = "../../Ribir/algo" }
ribir = { git = "https://github.com/RibirX/Ribir", features = ["png", "tokio-async"] }
ribir_algo = { git = "https://github.com/RibirX/Ribir" }

serde.workspace = true
serde_json.workspace = true
Expand Down
14 changes: 3 additions & 11 deletions gui/src/req.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use polestar_core::{
error::{PolestarError, PolestarResult},
model::{BotId, Channel, FeedbackMessageListForServer, Quota},
model::{AppInfo, BotId, FeedbackMessageListForServer, Quota},
service::{
open_ai::deal_open_ai_stream,
req::{create_text_request, fetch_feedback, req_feedback, request_quota},
Expand All @@ -10,20 +10,12 @@ use polestar_core::{
use ribir::prelude::*;

pub async fn query_open_ai(
channel: impl StateReader<Value = Channel>,
info: impl StateReader<Value = AppInfo>,
bot_id: BotId,
content: String,
delta_op: impl FnMut(String),
) -> Result<String, PolestarError> {
let req = {
let channel = channel.read();
let bot = channel
.bots()
.and_then(|bots| bots.iter().find(|bot| bot.id() == &bot_id))
.unwrap();
let info = channel.app_info().unwrap();
create_text_request(bot, info)
};
let req = { create_text_request(&info.read(), bot_id) };

let mut stream = req
.request(content)
Expand Down
4 changes: 2 additions & 2 deletions gui/src/style/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ pub static LIGHT_SILVER_15: u32 = 0xD9D9D915;
pub static LIGHT_SILVER_FF: u32 = 0xD9D9D9FF;
pub static WHITE: u32 = 0xFFFFFFFF;
pub static BRIGHT_GRAY_E9EEF7_FF: u32 = 0xE9EEF7FF;
pub static BRIGHT_GRAY_EEEDED_FF: u32 = 0xEEEEEDFF;
// pub static BRIGHT_GRAY_EEEDED_FF: u32 = 0xEEEEEDFF;
pub static ALICE_BLUE: u32 = 0xEDF7FBFF;
pub static GAINSBORO: u32 = 0xDCDBDAFF;
pub static GAINSBORO_DFDFDF_FF: u32 = 0xDFDFDFFF;
// pub static GAINSBORO_DFDFDF_FF: u32 = 0xDFDFDFFF;
pub static DARK_CHARCOAL: u32 = 0x333333FF;
pub static CHINESE_WHITE: u32 = 0xE0E0DEFF;
pub static ISABELLINE: u32 = 0xF1F1EFFF;
Expand Down
4 changes: 0 additions & 4 deletions gui/src/widgets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,3 @@ mod home;
mod login;
mod modify_channel;
mod permission;
mod quick_launcher;

pub use quick_launcher::launcher::*;
pub use quick_launcher::*;
Loading

0 comments on commit 585fc69

Please sign in to comment.