AnyBot/src/app/channels_ui.rs

1060 lines
60 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 訊息管道 in the window: the settings page, turning incoming messages into turns, and posting
// the bot's answer back when the turn ends.
use super::*;
use crate::channels::{self, Channel, Incoming, Kind, ReplyTo};
use std::collections::VecDeque;
/// How often the connectors are synced again: what failed or died is connected again.
const MCP_RETRY: std::time::Duration = std::time::Duration::from_secs(30);
pub struct ChannelUi {
pub tx: Sender<Incoming>,
pub rx: Receiver<Incoming>,
/// Where each bot's current answer goes back to.
pub replies: HashMap<u64, Vec<ReplyTo>>,
/// Messages that came while their bot was busy: each waits for a turn of its own.
waiting: VecDeque<Incoming>,
new_kind: Kind,
new_name: String,
new_token: String,
new_target: String,
new_bot: u64,
pub note: Arc<Mutex<String>>,
started: bool,
trig_tx: Sender<crate::triggers::Fired>,
trig_rx: Receiver<crate::triggers::Fired>,
/// What the running watchers were started with (restart when it changes).
trig_sig: String,
new_client: String,
new_tenant: String,
/// Teams sign-in: the code to show, and the refresh token when done.
ms_login: Arc<Mutex<(String, Option<String>)>>,
pub(super) mcp_sig: String,
pub(super) mcp_errors: Arc<Mutex<Vec<(String, String)>>>,
pub(super) mcp_busy: Arc<AtomicBool>,
/// When the connectors were last synced (again every half minute).
mcp_tried: Option<Instant>,
new_mcp: (String, String, String, String),
/// What the form needs from the person, for a server picked from the 公用市集.
new_mcp_hint: String,
/// 新增連接器's 帳號 and 密碼.
new_mcp_login: (String, String),
/// The form was just filled from the market: scroll it into view.
focus_form: bool,
/// 連接器: which added server's fields are unfolded (its place in the list).
pub(super) mcp_open: Option<usize>,
/// 公用市集 (the official MCP Registry): what is typed, a search on its way, what it found.
reg_q: String,
reg_busy: Arc<AtomicBool>,
reg_found: Arc<Mutex<Option<RegistryAnswer>>>,
/// 設定 › 整合's page: 0 訊息管道, 1 連接器, 2 技能.
pub sub: u8,
/// The form for a new channel is open (a press on one of 新增管道's tiles).
adding: bool,
/// 連接器市集 was asked for (scroll it into view once).
pub focus_market: bool,
skill_src: String,
skill_open: Option<String>,
/// The skill whose 「刪除」 was pressed once: it asks 「確定刪除」 before it goes (with its folder).
skill_confirm: Option<String>,
skill_busy: Arc<AtomicBool>,
skill_reload: Arc<AtomicBool>,
skill_note: Arc<Mutex<Option<(bool, String)>>>,
/// The last skill request came from the 技能 list (a delete): its answer shows there.
skill_note_list: bool,
}
impl Default for ChannelUi {
fn default() -> Self {
let (tx, rx) = channel();
let (trig_tx, trig_rx) = channel();
ChannelUi { tx, rx, replies: HashMap::new(), waiting: VecDeque::new(), new_kind: Kind::Telegram, new_name: String::new(), new_token: String::new(), new_target: String::new(), new_bot: 0, note: Default::default(), started: false, trig_tx, trig_rx, trig_sig: String::new(), new_client: String::new(), new_tenant: String::new(), ms_login: Default::default(), mcp_sig: String::new(), mcp_errors: Default::default(), mcp_busy: Default::default(), mcp_tried: None, new_mcp: Default::default(), sub: 0, adding: false, focus_market: false, skill_src: String::new(), skill_open: None, skill_confirm: None, skill_busy: Default::default(), skill_reload: Default::default(), skill_note: Default::default(), skill_note_list: false, new_mcp_hint: String::new(), new_mcp_login: Default::default(), focus_form: false, mcp_open: None, reg_q: String::new(), reg_busy: Default::default(), reg_found: Default::default() }
}
}
/// The waiting messages whose turn can start now: the oldest one of each bot that is free, in
/// the order they came. The rest stay, in order.
fn ready_messages(waiting: &mut VecDeque<Incoming>, busy: impl Fn(u64) -> bool) -> Vec<Incoming> {
let (mut ready, mut later): (Vec<Incoming>, VecDeque<Incoming>) = (vec![], VecDeque::new());
while let Some(m) = waiting.pop_front() {
if busy(m.bot_id) || ready.iter().chain(later.iter()).any(|w| w.bot_id == m.bot_id) {
later.push_back(m);
} else {
ready.push(m);
}
}
*waiting = later;
ready
}
impl App {
pub(super) fn channels_restart(&mut self, ctx: &egui::Context) {
if self.demo {
return;
}
let c = ctx.clone();
channels::restart(self.state.channels.clone(), self.ch.tx.clone(), Arc::new(move || c.request_repaint()));
self.ch.started = true;
}
/// Event-triggered routines: (re)start their watchers when they change, and run them when they fire.
fn triggers_poll(&mut self, ctx: &egui::Context) {
let watches: Vec<crate::triggers::Watch> = self
.state
.bots
.iter()
.flat_map(|b| b.routines.iter().filter(|r| !r.paused).filter_map(move |r| r.trigger.clone().map(|t| crate::triggers::Watch { bot_id: b.id, routine_id: r.id, trigger: t })))
.collect();
let sig = watches.iter().map(|w| format!("{}:{}:{:?}", w.bot_id, w.routine_id, w.trigger)).collect::<Vec<_>>().join("|");
if sig != self.ch.trig_sig {
self.ch.trig_sig = sig;
let slack = self.state.channels.iter().find(|c| c.kind == Kind::Slack && !c.token.trim().is_empty()).map(|c| c.token.clone()).unwrap_or_default();
let c = ctx.clone();
crate::triggers::restart(watches, slack, self.ch.trig_tx.clone(), Arc::new(move || c.request_repaint()));
}
while let Ok(f) = self.ch.trig_rx.try_recv() {
let Some(b) = self.state.bot_mut(f.bot_id) else { continue };
let Some(r) = b.routines.iter_mut().find(|r| r.id == f.routine_id) else { continue };
if r.paused {
continue;
}
r.last_run = Some(crate::routines::now());
let text = format!("[觸發]例行任務「{}」被觸發:{}\n要做的事:{}", r.title, f.what, r.prompt);
self.wake(ctx, f.bot_id, Message { wake: true, ..Message::user(&text) });
self.dirty = true;
}
}
/// New messages from Slack / Discord / Telegram wake their bot.
pub(super) fn channels_poll(&mut self, ctx: &egui::Context) {
if !self.ch.started {
self.channels_restart(ctx);
}
self.triggers_poll(ctx);
self.mcp_poll(ctx);
// Microsoft rotates refresh tokens: keep the newest.
let rotated: Vec<(u64, String)> = crate::teams::rotated().lock().unwrap().iter().map(|(k, v)| (*k, v.clone())).collect();
for (id, tok) in rotated {
if let Some(c) = self.state.channels.iter_mut().find(|c| c.id == id && c.token != tok) {
c.token = tok;
self.dirty = true;
}
}
while let Ok(m) = self.ch.rx.try_recv() {
self.ch.waiting.push_back(m);
}
self.ch.waiting.retain(|m| self.state.bot(m.bot_id).is_some());
// A message from a channel gets a turn of its own, when its bot is free. It used to be
// dropped into whatever turn was running, and that turn's answer (to the person's own
// question at the desk, say) was what went out to the channel.
let mut waiting = std::mem::take(&mut self.ch.waiting);
let ready = ready_messages(&mut waiting, |id| {
self.streams.contains_key(&id)
|| self.ch.replies.contains_key(&id)
|| self.group_next.contains(&id)
|| self.pending_turns.iter().any(|(b, _)| *b == id)
|| self.waiting_wakes.iter().any(|(b, _)| *b == id)
|| self.group_queue.get(&id).is_some_and(|q| !q.is_empty())
});
self.ch.waiting = waiting;
for m in ready {
let text = format!("[訊息管道]{}「{}」的 {}:{}", m.reply.kind.label(), m.reply.channel_name, m.from, m.text);
self.ch.replies.entry(m.bot_id).or_default().push(m.reply.clone());
self.wake(ctx, m.bot_id, Message { wake: true, untrusted_sender: true, memories_set: true, ..Message::user(&text) });
// No turn started (a group with nobody in it): nothing will answer, so no later
// turn's answer may go there either. (A screen's turns run on its brain.)
if !self.streams.contains_key(&m.bot_id) && !self.mir.on {
self.ch.replies.remove(&m.bot_id);
}
self.dirty = true;
}
if !self.ch.waiting.is_empty() {
ctx.request_repaint_after(std::time::Duration::from_millis(500));
}
}
/// The turn ended: send its answer back where the message came from.
pub(super) fn channels_settled(&mut self, bot_id: u64, outcome: TurnOutcome) {
let Some(targets) = self.ch.replies.remove(&bot_id) else { return };
let answer = match outcome {
TurnOutcome::Success => self.state.bot(bot_id).and_then(|b| b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.trim().is_empty() && !m.error)).map(|m| m.text.clone()),
TurnOutcome::Error => Some("抱歉,這次沒有完成,請再試一次。".to_string()),
TurnOutcome::Cancelled => None,
};
let Some(answer) = answer else { return };
let note = self.ch.note.clone();
std::thread::spawn(move || {
for t in targets {
if let Err(e) = channels::reply(&t, &answer) {
*note.lock().unwrap() = format!("回覆到 {}「{}」失敗:{e}", t.kind.label(), t.channel_name);
}
}
});
}
pub(super) fn channels_page(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
let p = self.pal;
// 已連接: what there is, each on a line — what it is, who answers, how it stands, on or off.
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 4.0;
ui.label(RichText::new(t("已連接")).size(FONT_XS).family(crate::bold()).color(p.text2));
help_mark(ui, "讓 Bot 在 Slack、Discord、Telegram、Microsoft Teams、Mac 的「訊息」或「郵件」回覆別人。收到訊息時 Bot 會像收到你的訊息一樣開始工作,做完後把回答傳回去(Slack 回在討論串,Discord 和 Telegram 引用原訊息)。AnyBot 開著時才會收訊息。", p);
});
ui.add_space(4.0);
let mut remove = None;
let mut changed = false;
let statuses = channels::statuses().lock().unwrap().clone();
let bots: Vec<(u64, String)> = self.state.bots.iter().map(|b| (b.id, b.name.clone())).collect();
rows_card(ui, p, |ui| {
if self.state.channels.is_empty() {
ui.add_space(16.0);
ui.label(RichText::new(t("還沒有連接任何管道。從下面挑一個開始。")).size(FONT_BASE).color(p.text2));
ui.add_space(16.0);
}
for (i, c) in self.state.channels.iter_mut().enumerate() {
let top = ui.cursor().top();
if i > 0 {
ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.border));
}
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 64.0), egui::Sense::hover());
kind_tile(ui, egui::Rect::from_min_size(egui::pos2(rect.left(), rect.center().y - 18.0), vec2(36.0, 36.0)), c.kind, p);
// From the right: ⋯, the switch, how it stands.
let mut right = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(Layout::right_to_left(Align::Center)));
right.spacing_mut().item_spacing.x = 10.0;
let more = crate::icons::button(&mut right, crate::icons::Icon::More, 30.0, p.text2, p.hover).on_hover_text(t("更多"));
egui::Popup::menu(&more).show(|ui| {
ui.set_min_width(menu_ui::MENU_W);
if menu_ui::danger(ui, p, crate::icons::Icon::Trash, "移除這個管道").clicked() {
remove = Some(i);
ui.close();
}
});
if right.add(computers_ui::toggle(&mut c.enabled)).changed() {
changed = true;
}
let (col, text) = match statuses.get(&c.id) {
_ if !c.enabled => (p.text3, t("已暫停")),
Some(s) if s.ok => (p.up, if s.received > 0 { format!("{}(收到 {} 則)", s.note, s.received) } else { s.note.clone() }),
Some(s) => (p.danger, s.note.clone()),
None => (p.text3, t("連線中…")),
};
let room = (right.available_width() - 36.0 - 150.0).clamp(60.0, 200.0);
right.label(RichText::new(sidebar_ui::shorten_width(&right, &text, room, 12.0)).size(FONT_XS).color(if col == p.text3 { p.text2 } else { col }));
let (dot, _) = right.allocate_exact_size(vec2(8.0, 8.0), egui::Sense::hover());
right.painter().circle_filled(dot.center(), 4.0, col);
// The words, in the room that is left.
let words = egui::Rect::from_min_max(egui::pos2(rect.left() + 48.0, rect.top()), egui::pos2((right.min_rect().left() - 10.0).max(rect.left() + 120.0), rect.bottom()));
let mut left = ui.new_child(egui::UiBuilder::new().max_rect(words).layout(Layout::top_down(Align::Min)));
left.spacing_mut().item_spacing.y = 1.0;
left.add_space(12.0);
left.add(egui::Label::new(RichText::new(format!("{} · {}", c.name, c.kind.label())).size(FONT_BASE).color(p.text)).truncate());
let bot = bots.iter().find(|b| b.0 == c.bot_id).map(|b| b.1.clone()).unwrap_or_else(|| t("(Bot 已刪除)"));
let whom = if c.target.is_empty() { t("{bot} 回覆").replace("{bot}", &bot) } else { format!("{} · {}", t("{bot} 回覆").replace("{bot}", &bot), c.target) };
left.add(egui::Label::new(RichText::new(whom).size(FONT_SM).color(p.text2)).truncate());
}
});
if let Some(i) = remove {
self.state.channels.remove(i);
changed = true;
}
// 新增管道: the kinds as tiles; a press opens that kind's form below.
ui.add_space(14.0);
ui.label(RichText::new(t("新增管道")).size(FONT_XS).family(crate::bold()).color(p.text2));
ui.add_space(4.0);
let kinds = [Kind::Telegram, Kind::Slack, Kind::Discord, Kind::Teams, Kind::IMessage, Kind::Email, Kind::Sms, Kind::X];
let cols = if ui.available_width() < 470.0 { 2 } else { 4 };
let (gap, w) = (10.0, (ui.available_width() - 10.0 * (cols as f32 - 1.0)) / cols as f32);
for row in kinds.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = gap;
for k in row {
let (rect, r) = ui.allocate_exact_size(vec2(w, 56.0), egui::Sense::click());
let on = self.ch.adding && self.ch.new_kind == *k;
ui.painter().rect_filled(rect, R_L, if r.hovered() { p.hover } else { p.elevated });
ui.painter().rect_stroke(rect, R_L, if on { Stroke::new(2.0, p.text) } else { Stroke::new(1.0, p.border) }, egui::StrokeKind::Inside);
kind_tile(ui, egui::Rect::from_min_size(egui::pos2(rect.left() + 12.0, rect.center().y - 16.0), vec2(32.0, 32.0)), *k, p);
let name = sidebar_ui::shorten_width(ui, k.label(), w - 62.0, FONT_BASE);
ui.painter().text(egui::pos2(rect.left() + 54.0, rect.center().y), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(FONT_BASE), p.text);
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
if self.ch.new_kind != *k {
self.ch.new_token.clear();
self.ch.new_target.clear();
}
self.ch.adding = !on;
self.ch.new_kind = *k;
}
}
});
ui.add_space(gap - 6.0);
}
if !self.ch.adding {
hint(ui, "點一個,才打開它的表單(名稱、回覆的 Bot、Token)。", p);
}
let mut added = false;
if self.ch.adding {
ui.add_space(6.0);
setting_card(ui, p, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(format!("{} {}", t("新增"), self.ch.new_kind.label())).size(FONT_BASE).family(crate::bold()).color(p.text));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if small_button(ui, "取消", p).clicked() {
added = true;
}
});
});
ui.add_space(4.0);
let k = self.ch.new_kind;
if self.ch.new_bot == 0 || !bots.iter().any(|b| b.0 == self.ch.new_bot) {
self.ch.new_bot = self.state.selected;
}
form_row(ui, "名稱", p, |ui| {
ui.add(egui::TextEdit::singleline(&mut self.ch.new_name).hint_text(t("例如 客服群")).desired_width(ui.available_width()));
});
form_row(ui, "回覆的 Bot", p, |ui| {
let cur = bots.iter().find(|b| b.0 == self.ch.new_bot).map(|b| b.1.clone()).unwrap_or_default();
egui::ComboBox::from_id_salt("channel-bot").selected_text(cur).show_ui(ui, |ui| {
for (id, name) in &bots {
ui.selectable_value(&mut self.ch.new_bot, *id, name);
}
});
});
if k == Kind::Teams {
form_row(ui, "應用程式 ID", p, |ui| {
ui.add(egui::TextEdit::singleline(&mut self.ch.new_client).hint_text(t("Entra 應用程式(用戶端)ID")).desired_width(ui.available_width()).font(egui::TextStyle::Monospace));
});
form_row(ui, "租用戶", p, |ui| {
ui.add(egui::TextEdit::singleline(&mut self.ch.new_tenant).hint_text(t("留空 = 公司或學校帳號")).desired_width(ui.available_width()).font(egui::TextStyle::Monospace));
});
hint(ui, k.token_hint(), p);
// A finished sign-in fills the token.
if let Some(tok) = self.ch.ms_login.lock().unwrap().1.take() {
self.ch.new_token = tok;
}
ui.horizontal(|ui| {
let signed = !self.ch.new_token.is_empty();
if ui.add_enabled(!self.ch.new_client.trim().is_empty(), secondary_button(if signed { "重新登入 Microsoft" } else { "登入 Microsoft" })).clicked() {
let (client, tenant, slot, c) = (self.ch.new_client.clone(), self.ch.new_tenant.clone(), self.ch.ms_login.clone(), ctx.clone());
slot.lock().unwrap().0 = "正在取得登入代碼…".into();
std::thread::spawn(move || {
match crate::teams::device_code(&client, &tenant) {
Ok((code, url, device, interval)) => {
slot.lock().unwrap().0 = format!("在打開的網頁輸入代碼:{code}({url})");
crate::preview::open_with_system(&url);
c.request_repaint();
let r = crate::teams::wait_for_login(&client, &tenant, &device, interval, std::time::Duration::from_secs(900));
let mut s = slot.lock().unwrap();
match r {
Ok(t) => {
s.0 = "已登入 Microsoft。".into();
s.1 = Some(t);
}
Err(e) => s.0 = e,
}
}
Err(e) => slot.lock().unwrap().0 = format!("拿不到登入代碼:{e}"),
}
c.request_repaint();
});
}
let msg = self.ch.ms_login.lock().unwrap().0.clone();
if !msg.is_empty() {
ui.label(RichText::new(msg).size(FONT_SM).color(p.text2));
}
});
} else if matches!(k, Kind::IMessage | Kind::Email) {
hint(ui, k.token_hint(), p);
self.ch.new_token = "local".into();
} else {
form_row(ui, "Token", p, |ui| {
ui.add(egui::TextEdit::singleline(&mut self.ch.new_token).password(true).hint_text(t("貼上 Bot Token")).desired_width(ui.available_width()));
});
hint(ui, k.token_hint(), p);
}
form_row(ui, match k { Kind::Telegram => "聊天 ID", Kind::Teams => "聊天或頻道", Kind::IMessage => "對象", Kind::Email => "信箱", Kind::Sms => "你的號碼", Kind::X => "(不用填)", _ => "頻道 ID" }, p, |ui| {
ui.add(egui::TextEdit::singleline(&mut self.ch.new_target).hint_text(k.target_hint()).desired_width(ui.available_width()).font(egui::TextStyle::Monospace));
});
let needs_target = !matches!(k, Kind::Telegram | Kind::IMessage | Kind::Email | Kind::X);
let ok = !self.ch.new_token.trim().is_empty() && (!needs_target || !self.ch.new_target.trim().is_empty());
ui.horizontal(|ui| {
if k != Kind::Teams && ui.add_enabled(!self.ch.new_token.trim().is_empty(), secondary_button(if matches!(k, Kind::IMessage | Kind::Email) { "測試" } else { "測試 Token" })).clicked() {
let (kind, token, note) = (k, self.ch.new_token.clone(), self.ch.note.clone());
*note.lock().unwrap() = "測試中…".into();
let c = ctx.clone();
std::thread::spawn(move || {
*note.lock().unwrap() = channels::test(kind, &token).unwrap_or_else(|e| e);
c.request_repaint();
});
}
if ui.add_enabled(ok, primary_button("新增", p)).clicked() {
let id = self.state.next_channel_id.max(1);
self.state.next_channel_id = id + 1;
let name = if self.ch.new_name.trim().is_empty() { k.label().to_string() } else { self.ch.new_name.trim().to_string() };
self.state.channels.push(Channel { id, kind: k, name, bot_id: self.ch.new_bot, token: self.ch.new_token.trim().into(), target: self.ch.new_target.trim().into(), enabled: true, client_id: self.ch.new_client.trim().into(), tenant: self.ch.new_tenant.trim().into() });
self.ch.new_client.clear();
self.ch.new_tenant.clear();
self.ch.new_name.clear();
self.ch.new_token.clear();
self.ch.new_target.clear();
changed = true;
added = true;
}
});
let note = self.ch.note.lock().unwrap().clone();
if !note.is_empty() {
ui.label(RichText::new(note).size(FONT_SM).color(p.text2));
}
});
}
if added {
self.ch.adding = false;
}
if changed {
self.dirty = true;
self.channels_restart(ctx);
}
}
}
// ---------- 連接器 (MCP) ----------
impl App {
/// Connect the configured MCP servers when they change (in the background), and re-sync
/// every half minute: sync keeps what is alive and connects again what failed or died, so a
/// server that wasn't up yet, crashed, or lost its machine comes back on its own.
fn mcp_poll(&mut self, ctx: &egui::Context) {
if self.ch.mcp_busy.load(Ordering::SeqCst) {
return;
}
let sig = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default();
if sig == self.ch.mcp_sig && self.ch.mcp_tried.is_some_and(|t| t.elapsed() < MCP_RETRY) {
return;
}
self.ch.mcp_sig = sig;
self.ch.mcp_tried = Some(Instant::now());
let servers = self.state.mcp_servers.clone();
let (errs, busy, c) = (self.ch.mcp_errors.clone(), self.ch.mcp_busy.clone(), ctx.clone());
busy.store(true, Ordering::SeqCst);
std::thread::spawn(move || {
*errs.lock().unwrap() = crate::mcp::sync(&servers);
busy.store(false, Ordering::SeqCst);
c.request_repaint();
});
}
/// 重新連線 (here, or asked by a screen or the phone): drop the server's link and connect it
/// again now; its line says 連線中… until the answer.
pub(super) fn mcp_reconnect(&mut self, name: &str) {
crate::mcp::forget(name);
self.ch.mcp_errors.lock().unwrap().retain(|e| e.0 != name);
self.ch.mcp_sig.clear();
}
/// The servers' state as 連接器 shows it: {servers: {name: {tools, error}}, busy, tools:
/// [[server, tool, description]]}. A screen gets the brain's (its own would say 未連線).
pub(super) fn mcp_state(&self) -> serde_json::Value {
let status = crate::mcp::status();
let errors = self.ch.mcp_errors.lock().unwrap().clone();
let servers: serde_json::Map<String, serde_json::Value> = self
.state
.mcp_servers
.iter()
.map(|s| (s.name.clone(), serde_json::json!({"tools": status.get(&s.name), "error": errors.iter().find(|e| e.0 == s.name).map(|e| e.1.clone())})))
.collect();
let tools: Vec<serde_json::Value> = crate::mcp::tools().iter().take(60).map(|t| serde_json::json!([t.server, t.name, t.description.chars().take(300).collect::<String>()])).collect();
serde_json::json!({"servers": servers, "busy": self.ch.mcp_busy.load(Ordering::SeqCst), "tools": tools})
}
/// 連接器 (`part` 1: the servers, their tools, the markets, the form) and 技能 (`part` 2).
pub(super) fn connectors_page(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, part: u8) {
let p = self.pal;
let before = serde_json::to_string(&self.state.mcp_servers).unwrap_or_default();
if part == 1 {
setting_card(ui, p, |ui| {
setting_title(ui, "連接器(MCP)", "接上 Model Context Protocol 伺服器,Bot 就能用它的工具(例如 GitHub、Notion、資料庫、你公司的內部系統)。每個連接器第一次被使用時會先問你。", p);
hint(ui, "本機伺服器填指令(例如 npx -y @modelcontextprotocol/server-filesystem ~/Documents);遠端伺服器填網址(Streamable HTTP),需要時加上 Authorization 標頭。", p);
});
// On a screen the servers run at the brain: its state, not this computer's.
let st = if self.mir.on { self.mir.mcp_state.clone() } else { self.mcp_state() };
let busy = st["busy"].as_bool().unwrap_or(false);
// (「這台電腦沒有 Node.js」 from the brain means the brain, not the computer in front.)
let at = if self.mir.on { "在大腦上:" } else { "" };
let mut remove = None;
let mut reconnect = None;
// The servers as one list (a row each: name, its state, 設定, the switch); the one being
// set up unfolds its fields under its row — every name above its box, all boxes alike.
let open_now = self.ch.mcp_open;
let mut open_next = open_now;
if !self.state.mcp_servers.is_empty() {
section(ui, "已加入", p);
rows_card(ui, p, |ui| {
for (i, s) in self.state.mcp_servers.iter_mut().enumerate() {
let one = &st["servers"][s.name.as_str()];
let (col, text) = match (s.enabled, one["tools"].as_u64(), one["error"].as_str()) {
(false, _, _) => (p.text3, "已關閉".to_string()),
(_, Some(n), _) => (p.up, format!("已連上,{n} 個工具")),
(_, _, Some(e)) => (p.danger, format!("{at}{e}")),
_ if busy => (p.text3, "連線中…".to_string()),
_ => (p.text3, "未連線".to_string()),
};
let open = open_now == Some(i);
let name = s.name.clone();
status_row(ui, p, &name, &text, col, |ui| {
ui.add(computers_ui::toggle(&mut s.enabled)).on_hover_text(t("開啟"));
if ui.add(secondary_button(if open { "收起" } else { "設定" })).clicked() {
open_next = if open { None } else { Some(i) };
}
});
if !open {
continue;
}
// 全部欄位都能改:改了就存(頁面尾端的簽名比對會標 dirty),mcp_poll 偵測到
// 簽名變動會自動重連。
let mut cmd_edit = if s.url.is_empty() { format!("{} {}", s.command, s.args.join(" ")).trim().to_string() } else { s.url.clone() };
let mut env_edit: String = s.env.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join(" ");
let mut hdr_edit: String = s.headers.iter().map(|(k, v)| format!("{k}: {v}")).collect::<Vec<_>>().join(" ");
let hide_hdr = !hdr_edit.contains('{') && !hdr_edit.is_empty();
let (mut cmd_changed, mut env_changed, mut hdr_changed) = (false, false, false);
form_row(ui, "名稱", p, |ui| {
ui.add(egui::TextEdit::singleline(&mut s.name).desired_width(ui.available_width()));
});
form_row(ui, "指令或網址", p, |ui| {
cmd_changed = ui.add(egui::TextEdit::singleline(&mut cmd_edit).font(egui::TextStyle::Monospace).hint_text(t("npx -y … 或 https://…/mcp")).desired_width(ui.available_width())).changed();
});
form_row(ui, "環境變數", p, |ui| {
env_changed = ui.add(egui::TextEdit::singleline(&mut env_edit).font(egui::TextStyle::Monospace).password(true).hint_text(t("K=V K2=V2(本機用,選填)")).desired_width(ui.available_width())).changed();
});
form_row(ui, "標頭", p, |ui| {
hdr_changed = ui.add(egui::TextEdit::singleline(&mut hdr_edit).font(egui::TextStyle::Monospace).password(hide_hdr).hint_text(t("Authorization: Bearer …(遠端用,選填)")).desired_width(ui.available_width())).changed();
});
if cmd_changed {
let c = cmd_edit.trim().to_string();
if c.starts_with("http://") || c.starts_with("https://") {
s.url = c;
s.command.clear();
s.args.clear();
} else {
let mut it = c.split_whitespace();
s.command = it.next().unwrap_or_default().to_string();
s.args = it.map(String::from).collect();
s.url.clear();
}
}
if env_changed {
s.env = env_edit.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect();
}
if hdr_changed {
s.headers = hdr_edit.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default();
}
if s.name != s.name.trim() {
s.name = s.name.trim().to_string();
}
// 帳號 / 密碼: changed here, the server is connected again with the new ones.
let (user, pass) = (&mut s.username, &mut s.password);
form_pair(
ui,
p,
"帳號",
|ui| {
ui.add(egui::TextEdit::singleline(user).hint_text(t("選填")).desired_width(ui.available_width()));
},
"密碼",
|ui| {
ui.add(egui::TextEdit::singleline(pass).password(true).hint_text(t("選填")).desired_width(ui.available_width()));
},
);
form_row(ui, "給 Bot 的使用說明(選填)", p, |ui| {
ui.add(egui::TextEdit::multiline(&mut s.instructions).desired_rows(1).desired_width(ui.available_width()).hint_text(t("例如:查詢客戶資料時先用 search_customers")));
});
// Its own actions, at the end of what they act on: 移除 on the left, away from the rest.
ui.add_space(crate::theme::sp::S3);
ui.horizontal(|ui| {
if ui.add(egui::Button::new(RichText::new(t("移除")).color(p.danger)).frame(false)).clicked() {
remove = Some(i);
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if s.enabled && ui.add(secondary_button("重新連線")).on_hover_text(t("再連一次,看連不連得上")).clicked() {
reconnect = Some(s.name.clone());
}
});
});
ui.add_space(crate::theme::sp::S3);
}
});
}
if remove.is_some() {
open_next = None;
}
self.ch.mcp_open = open_next;
if let Some(i) = remove {
self.state.mcp_servers.remove(i);
}
if let Some(name) = reconnect {
if self.mir.on {
self.mirror_mcp_reconnect(&name);
} else {
self.mcp_reconnect(&name);
}
}
let tools: Vec<&serde_json::Value> = st["tools"].as_array().into_iter().flatten().collect();
if !tools.is_empty() {
setting_card(ui, p, |ui| {
setting_title(ui, "可以用的工具", "", p);
for t in tools {
let s = |i: usize| t[i].as_str().unwrap_or("");
ui.label(RichText::new(format!("{} · {}", s(0), s(1))).size(FONT_SM).color(p.text2)).on_hover_text(s(2));
}
});
}
}
// A finished install: this computer's skill folder joins the list. (Not on a screen: its
// list is the brain's, and the brain installs there itself.)
if self.ch.skill_reload.swap(false, Ordering::SeqCst) && !self.mir.on {
crate::memory::merge_skill_files(&mut self.state.skills);
self.dirty = true;
}
let skill_busy = self.ch.skill_busy.load(Ordering::SeqCst);
if part == 2 {
setting_card(ui, p, |ui| {
setting_title(ui, "技能", "所有 Bot 共用的專業指南與標準作業流程(相容 Agent Skills SKILL.md 規格,支援隨附 scripts/ 與 references/)。開啟的技能會列在 Bot 的目錄中,需要時自動載入。", p);
if self.state.skills.is_empty() {
hint(ui, "還沒有技能。可從下方「技能市集」一鍵加入。", p);
}
let mut remove = None;
let mut dirty_toggle = false;
for (i, k) in self.state.skills.iter_mut().enumerate() {
let is_open = self.ch.skill_open.as_deref() == Some(k.name.as_str());
let name_col = if k.enabled { p.text } else { p.text3 };
let (name, description) = (k.name.clone(), k.description.clone());
let (files, steps) = (k.resources.len(), k.steps.len());
listing_row(
ui,
|ui| {
// Two presses: it goes with its folder (scripts and all), and can't come back.
if self.ch.skill_confirm.as_deref() == Some(name.as_str()) {
if ui.add(egui::Button::new(RichText::new(t("取消")).size(FONT_SM).color(p.text2)).frame(false)).clicked() {
self.ch.skill_confirm = None;
}
if ui.add(egui::Button::new(RichText::new(t("確定刪除(連檔案)")).size(FONT_XS).color(p.danger)).frame(false)).clicked() {
remove = Some(i);
self.ch.skill_confirm = None;
}
} else if ui.add(egui::Button::new(RichText::new(t("刪除")).size(FONT_XS).color(p.danger)).frame(false)).clicked() {
self.ch.skill_confirm = Some(name.clone());
}
if ui.add(egui::Button::new(RichText::new(t(if is_open { "收起" } else { "檢視" })).size(FONT_SM).color(p.text2)).frame(false)).clicked() {
self.ch.skill_open = if is_open { None } else { Some(name.clone()) };
}
if ui.add(computers_ui::toggle(&mut k.enabled)).on_hover_text(t("開啟")).changed() {
dirty_toggle = true;
}
},
|ui| {
// (長的技能名字在行尾的按鈕前截斷,不會壓到「檢視」。)
ui.add(egui::Label::new(RichText::new(&name).strong().family(crate::bold()).size(FONT_SM).color(name_col)).truncate()).on_hover_text(&description);
if files > 0 {
ui.label(RichText::new(format!("{files} 檔")).size(FONT_XS).color(p.accent));
}
if steps > 0 {
ui.label(RichText::new(format!("可重播 {steps} 步")).size(FONT_XS).color(p.text3));
}
ui.add(egui::Label::new(RichText::new(&description).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(&description);
},
);
if is_open {
egui::Frame::new()
.fill(p.pane)
.stroke(Stroke::new(1.0, p.border))
.corner_radius(R_M)
.inner_margin(Margin::symmetric(10, 8))
.show(ui, |ui| {
if !k.resources.is_empty() {
ui.label(RichText::new(format!("隨附檔案:{}", k.resources.join("、"))).monospace().size(FONT_SM).color(p.text2));
ui.add_space(4.0);
}
let preview: String = k.instructions.chars().take(1800).collect();
ui.label(RichText::new(preview).size(FONT_SM).color(p.text2));
});
}
}
if dirty_toggle {
self.dirty = true;
}
if let Some(i) = remove {
if self.mir.on {
// The brain takes it off its list and its disk (a folder left there would
// bring it back when the brain restarts); the list here follows.
let name = self.state.skills[i].name.clone();
self.ch.skill_note_list = true;
self.mirror_skill(serde_json::json!({"name": name, "remove": true}), self.ch.skill_note.clone(), self.ch.skill_busy.clone());
} else {
let gone = self.state.skills.remove(i);
crate::memory::remove_skill_files(&gone.name);
if self.ch.skill_open.as_deref() == Some(gone.name.as_str()) {
self.ch.skill_open = None;
}
self.dirty = true;
}
}
if self.ch.skill_note_list {
skill_status(ui, &self.ch, skill_busy, p);
}
});
setting_card(ui, p, |ui| {
setting_title(ui, "技能市集", "內建繁體中文核心技能包離線即裝即用;也可從 Anthropic 官方 anthropics/skills 儲存庫或任意 GitHub 技能資料夾一鍵安裝。", p);
field_label(ui, "內建技能包", p);
let mut add_builtin = None;
for b in crate::skills::BUILTIN_SKILLS {
let added = self.state.skills.iter().any(|s| s.name == b.slug);
listing_row(
ui,
|ui| {
if added {
ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3));
} else if ui.add(secondary_button("加入")).clicked() {
add_builtin = Some(b.slug);
}
},
|ui| {
ui.label(RichText::new(b.slug).strong().family(crate::bold()).size(FONT_SM));
let about = format!("{} — {}", b.title, b.summary);
ui.add(egui::Label::new(RichText::new(&about).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(&about);
},
);
}
if let Some(slug) = add_builtin {
self.ch.skill_note_list = false;
if self.mir.on {
self.mirror_skill(serde_json::json!({"builtin": slug}), self.ch.skill_note.clone(), self.ch.skill_busy.clone());
} else {
match crate::skills::install_builtin(slug, &mut self.state.skills) {
Ok(name) => {
*self.ch.skill_note.lock().unwrap() = Some((true, format!("已加入技能「{name}」")));
self.dirty = true;
}
Err(e) => *self.ch.skill_note.lock().unwrap() = Some((false, e)),
}
}
}
ui.add_space(6.0);
field_label(ui, "Anthropic 開源技能精選(GitHub: anthropics/skills)", p);
let mut install = None;
for r in crate::skills::REMOTE_MARKET {
let added = self.state.skills.iter().any(|s| s.name == r.name);
listing_row(
ui,
|ui| {
if added {
ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3));
} else if ui.add_enabled(!skill_busy, secondary_button("安裝")).clicked() {
install = Some(r.source.to_string());
}
},
|ui| {
ui.label(RichText::new(r.name).strong().family(crate::bold()).size(FONT_SM));
ui.add(egui::Label::new(RichText::new(r.summary).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(r.summary);
},
);
}
ui.add_space(8.0);
field_label(ui, "從 GitHub、網址或本機資料夾安裝技能", p);
ui.horizontal(|ui| {
let btn_w = 72.0;
let w = (ui.available_width() - btn_w - 8.0).max(120.0);
let resp = ui.add(
egui::TextEdit::singleline(&mut self.ch.skill_src)
.hint_text(t("https://github.com/anthropics/skills/tree/main/skills/… 或本機路徑"))
.desired_width(w)
.font(egui::TextStyle::Monospace),
);
let can_install = !skill_busy && !self.ch.skill_src.trim().is_empty();
let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
if ui.add_enabled(can_install, primary_button("安裝", p)).clicked() || (can_install && enter) {
install = Some(std::mem::take(&mut self.ch.skill_src));
}
});
if let Some(src) = install {
self.skill_install(src, ctx);
}
if !self.ch.skill_note_list {
skill_status(ui, &self.ch, skill_busy, p);
}
});
}
if part == 1 {
// 外掛市集: common connectors, one click away (ones needing a key fill the form below).
setting_card(ui, p, |ui| {
if std::mem::take(&mut self.ch.focus_market) {
ui.scroll_to_cursor(Some(Align::TOP));
}
setting_title(ui, "連接器市集", "常用的連接器,按「加入」就能用。需要金鑰的會填好下面的表單,補上金鑰再按「新增」。本機的需要先裝 Node.js(npx)或 uv(uvx)。下面的「公用市集」搜尋官方 MCP Registry 裡用網址連的連接器。", p);
for (name, desc, cmd, needs) in crate::mcp::MARKET {
let added = self.state.mcp_servers.iter().any(|s| s.name == name);
listing_row(
ui,
|ui| {
if added {
ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3));
} else if ui.add(secondary_button("加入")).clicked() {
if needs.is_empty() {
self.state.mcp_servers.push(crate::mcp::market_server(name, cmd));
} else {
self.ch.new_mcp = (name.to_string(), cmd.to_string(), if cmd.starts_with("http") { String::new() } else { needs.to_string() }, if cmd.starts_with("http") { needs.to_string() } else { String::new() });
}
}
},
|ui| {
ui.label(RichText::new(name).strong().family(crate::bold()).size(FONT_SM));
ui.add(egui::Label::new(RichText::new(desc).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(desc);
},
);
}
self.registry_market(ui, ctx);
});
setting_card(ui, p, |ui| {
if std::mem::take(&mut self.ch.focus_form) {
ui.scroll_to_cursor(Some(Align::TOP));
}
setting_title(ui, "新增連接器", "", p);
let (name, cmd, env, headers) = &mut self.ch.new_mcp;
form_row(ui, "名稱", p, |ui| {
ui.add(egui::TextEdit::singleline(name).hint_text(t("例如 github")).desired_width(ui.available_width()));
});
form_row(ui, "指令或網址", p, |ui| {
ui.add(egui::TextEdit::singleline(cmd).hint_text(t("npx -y @modelcontextprotocol/server-github 或 https://…/mcp")).desired_width(ui.available_width()).font(egui::TextStyle::Monospace));
});
form_row(ui, "環境變數", p, |ui| {
ui.add(egui::TextEdit::singleline(env).hint_text(t("GITHUB_TOKEN=…(多個用空白分開,本機伺服器用)")).password(true).desired_width(ui.available_width()));
});
form_row(ui, "標頭", p, |ui| {
// Shown as typed while a 「{…}」 is still to be replaced; hidden once it's a key.
let hide = !headers.contains('{');
ui.add(egui::TextEdit::singleline(headers).hint_text(t("Authorization: Bearer …(遠端伺服器用)")).password(hide).desired_width(ui.available_width()));
});
let (user, pass) = &mut self.ch.new_mcp_login;
form_row(ui, "帳號", p, |ui| {
ui.add(egui::TextEdit::singleline(user).hint_text(t("要用帳號密碼登入的伺服器才填")).desired_width(ui.available_width()));
});
form_row(ui, "密碼", p, |ui| {
ui.add(egui::TextEdit::singleline(pass).password(true).desired_width(ui.available_width()));
});
hint(ui, "帳號密碼怎麼交給伺服器:在指令、環境變數、網址或標頭裡寫「{username}」「{password}」,就填在那裡(例如環境變數 SCC_USER={username} SCC_PASS={password});都沒寫的話,本機伺服器會收到環境變數 MCP_USERNAME、MCP_PASSWORD,遠端伺服器收到 Authorization: Basic。", p);
if !self.ch.new_mcp_hint.is_empty() {
ui.label(RichText::new(&self.ch.new_mcp_hint).size(FONT_SM).color(p.text2));
}
// A 「{…}」 left in the address or the header can only fail (the 帳號/密碼 slots are filled when connecting).
let unfilled = crate::mcp::Server::unfilled(cmd) || crate::mcp::Server::unfilled(headers);
if unfilled {
ui.label(RichText::new(t("還有「{…}」沒換成你的值")).size(FONT_XS).color(p.danger));
}
let ok = !unfilled && !name.trim().is_empty() && !cmd.trim().is_empty() && !self.state.mcp_servers.iter().any(|s| s.name == name.trim());
if ui.add_enabled(ok, primary_button("新增", p)).clicked() {
let c = cmd.trim().to_string();
let is_url = c.starts_with("http://") || c.starts_with("https://");
let parts: Vec<String> = c.split_whitespace().map(String::from).collect();
let envs = env.split_whitespace().filter_map(|kv| kv.split_once('=')).map(|(k, v)| (k.to_string(), v.to_string())).collect();
let hdrs = headers.split_once(':').map(|(k, v)| std::iter::once((k.trim().to_string(), v.trim().to_string())).collect()).unwrap_or_default();
self.state.mcp_servers.push(crate::mcp::Server {
name: name.trim().into(),
command: if is_url { String::new() } else { parts.first().cloned().unwrap_or_default() },
args: if is_url { vec![] } else { parts.into_iter().skip(1).collect() },
env: envs,
url: if is_url { c } else { String::new() },
headers: hdrs,
enabled: true,
instructions: String::new(),
username: user.trim().to_string(),
password: pass.clone(),
});
self.ch.new_mcp_login = Default::default();
self.ch.new_mcp = Default::default();
self.ch.new_mcp_hint.clear();
}
});
}
let _ = ctx;
if serde_json::to_string(&self.state.mcp_servers).unwrap_or_default() != before {
self.dirty = true;
}
}
}
impl App {
/// 公用市集: search the official MCP Registry (in the background) and list what it has that
/// is reached by address; 加入 fills 新增連接器 with the address and the header to complete.
fn registry_market(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
let p = self.pal;
ui.add_space(8.0);
field_label(ui, "公用市集(官方 MCP Registry)", p);
let busy = self.ch.reg_busy.load(Ordering::SeqCst);
let mut go = false;
ui.horizontal(|ui| {
let w = (ui.available_width() - 72.0 - 8.0).max(120.0);
let resp = ui.add(egui::TextEdit::singleline(&mut self.ch.reg_q).hint_text(t("搜尋用網址連的連接器,例如 notion、search、docs")).desired_width(w));
let can = !busy && !self.ch.reg_q.trim().is_empty();
let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
go = ui.add_enabled(can, primary_button("搜尋", p)).clicked() || (can && enter);
});
if go {
self.ch.reg_busy.store(true, Ordering::SeqCst);
let (q, busy, found, ctx) = (self.ch.reg_q.clone(), self.ch.reg_busy.clone(), self.ch.reg_found.clone(), ctx.clone());
std::thread::spawn(move || {
*found.lock().unwrap() = Some(crate::mcp::registry_search(&q));
busy.store(false, Ordering::SeqCst);
ctx.request_repaint();
});
}
if busy {
ui.label(RichText::new(t("搜尋中…")).size(FONT_XS).color(p.text3));
return;
}
let found = self.ch.reg_found.lock().unwrap().clone();
let list = match found {
None => return,
Some(Err(e)) => {
ui.label(RichText::new(e).size(FONT_XS).color(p.danger));
return;
}
Some(Ok(list)) if list.is_empty() => {
ui.label(RichText::new(t("沒有找到。換個關鍵字試試(英文的比較多)。")).size(FONT_XS).color(p.text3));
return;
}
Some(Ok(list)) => list,
};
let mut pick = None;
for (i, e) in list.iter().enumerate() {
let (title, about, url, note) = (e["title"].as_str().unwrap_or(""), e["description"].as_str().unwrap_or(""), e["url"].as_str().unwrap_or(""), e["note"].as_str().unwrap_or(""));
let added = self.state.mcp_servers.iter().any(|s| s.url == url);
listing_row(
ui,
|ui| {
if !note.is_empty() {
ui.label(RichText::new(t(note)).size(FONT_XS).color(p.text3));
} else if added {
ui.label(RichText::new(t("已加入")).size(FONT_XS).color(p.text3));
} else if ui.add(secondary_button("加入")).clicked() {
pick = Some(i);
}
},
|ui| {
ui.label(RichText::new(title).strong().family(crate::bold()).size(FONT_SM));
if e["header"].is_object() {
ui.label(RichText::new(t("要金鑰")).size(FONT_XS).color(p.accent));
}
ui.add(egui::Label::new(RichText::new(about).size(FONT_XS).color(p.text3)).truncate()).on_hover_text(format!("{about}\n{url}"));
},
);
}
if let Some(e) = pick.and_then(|i| list.get(i)) {
let (name, url, header, hint) = crate::mcp::registry_form(e, &self.state.mcp_servers);
self.ch.new_mcp = (name, url, String::new(), header);
self.ch.new_mcp_hint = hint;
self.ch.focus_form = true;
}
}
/// Screenshot mode: the 公用市集 with this search done.
pub(super) fn shot_registry(&mut self, q: &str) {
self.ch.reg_q = q.to_string();
*self.ch.reg_found.lock().unwrap() = Some(crate::mcp::registry_search(q));
}
/// Install a skill from an address or a folder. On a screen the brain does it — it fetches
/// an address itself, and a folder on this computer goes up whole — since the bots read skills
/// from the brain's disk. Otherwise it is fetched in the background and the list reloads.
fn skill_install(&mut self, src: String, ctx: &egui::Context) {
self.ch.skill_note_list = false;
let (busy, note) = (self.ch.skill_busy.clone(), self.ch.skill_note.clone());
let src = src.trim().to_string();
if self.mir.on {
let body = if crate::tools::expand_home(&src).exists() { serde_json::json!({"local": src}) } else { serde_json::json!({"install": src}) };
self.mirror_skill(body, note, busy);
return;
}
if busy.swap(true, Ordering::SeqCst) {
return;
}
*note.lock().unwrap() = None;
let (reload, ctx) = (self.ch.skill_reload.clone(), ctx.clone());
std::thread::spawn(move || {
*note.lock().unwrap() = Some(match crate::skills::install_from_source(&src) {
Ok(name) => {
reload.store(true, Ordering::SeqCst);
(true, format!("已安裝技能「{name}」"))
}
Err(e) => (false, e),
});
busy.store(false, Ordering::SeqCst);
ctx.request_repaint();
});
}
}
/// How the last skill request went (or that it is still on its way).
fn skill_status(ui: &mut egui::Ui, ch: &ChannelUi, busy: bool, p: Palette) {
if busy {
ui.label(RichText::new(t("處理中…")).size(FONT_XS).color(p.text3));
} else if let Some((ok, msg)) = ch.skill_note.lock().unwrap().clone() {
ui.label(RichText::new(msg).size(FONT_XS).color(if ok { p.up } else { p.danger }));
}
}
/// What a 公用市集 search found (rows as `mcp::registry_entries` gives them), or why it failed.
type RegistryAnswer = Result<Vec<serde_json::Value>, String>;
/// A channel kind's mark: its first letter on a quiet tint of its own (no logos).
fn kind_tile(ui: &egui::Ui, rect: egui::Rect, k: Kind, p: Palette) {
let (letter, rgb): (&str, [u8; 3]) = match k {
Kind::Telegram => ("T", [0x0f, 0x4c, 0x8a]),
Kind::Slack => ("S", [0x5b, 0x2a, 0x86]),
Kind::Discord => ("D", [0x3a, 0x3f, 0x9e]),
Kind::Teams => ("M", [0x43, 0x38, 0xa8]),
Kind::IMessage => ("訊", [0x0b, 0x6b, 0x3d]),
Kind::Email => ("郵", [0x9a, 0x34, 0x12]),
Kind::Sms => ("簡", [0xa1, 0x1d, 0x2b]),
Kind::X => ("X", [0x1c, 0x1c, 0x1c]),
};
let ink = Color32::from_rgb(rgb[0], rgb[1], rgb[2]);
let dark = p.pane.r() < 128;
ui.painter().rect_filled(rect, R_M, crate::theme::mist(ink, Palette { pane: if dark { Color32::from_rgb(0x30, 0x30, 0x30) } else { Color32::WHITE }, ..p }).gamma_multiply(1.0));
let col = if dark { Color32::from_rgb(0xf0, 0xf0, 0xf0) } else { ink };
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, letter, egui::FontId::new(FONT_BASE, crate::bold()), col);
}
/// One line of a list: its buttons on the right (`buttons` adds them rightmost first), and the
/// words on the left in the room that is left — a long description ends in … before the
/// buttons instead of running under them.
fn listing_row(ui: &mut egui::Ui, buttons: impl FnOnce(&mut egui::Ui), words: impl FnOnce(&mut egui::Ui)) {
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
buttons(ui);
ui.with_layout(Layout::left_to_right(Align::Center), words);
});
});
}
#[cfg(test)]
mod tests {
use super::*;
/// A message from a channel never joins a turn that is running: it waits for its own.
#[test]
fn a_channel_message_waits_for_a_turn_of_its_own() {
let msg = |bot_id: u64, text: &str| Incoming { bot_id, from: "ann".into(), text: text.into(), reply: ReplyTo { kind: Kind::Telegram, token: String::new(), target: "1".into(), thread: String::new(), channel_name: "c".into() } };
let texts = |v: &[Incoming]| v.iter().map(|m| m.text.clone()).collect::<Vec<_>>();
let mut waiting: VecDeque<Incoming> = [msg(1, "a"), msg(2, "b"), msg(1, "c"), msg(3, "d")].into();
// Bot 2 is in the middle of the person's own question: its message stays.
let ready = ready_messages(&mut waiting, |id| id == 2);
assert_eq!(texts(&ready), ["a", "d"]);
assert_eq!(texts(&waiting.iter().cloned().collect::<Vec<_>>()), ["b", "c"]);
// Later, everyone is free: one message each, the oldest first.
let ready = ready_messages(&mut waiting, |_| false);
assert_eq!(texts(&ready), ["b", "c"]);
assert!(waiting.is_empty());
}
}