Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ tauri-plugin-deep-link = "2"
# 编出来的东西不一样;而更要紧的是,打进 `.app` 的那个 twcore 二进制
# 必须和这里编译进去的协议镜像来自同一个 core 版本 —— 打包脚本正是从
# 这个 tag 去取二进制的(见 scripts/fetch-core.sh)。
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.24.1" }
tw-api = { git = "https://github.com/ThinkWatchProject/ThinkWatch-Core.git", tag = "v0.25.0" }

anyhow = "1"
libc = "0.2"
Expand Down
7 changes: 5 additions & 2 deletions src-tauri/src/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1055,12 +1055,14 @@ impl ControlClient {
Ok(serde_json::from_slice(&body)?)
}

/// 订阅事件流,逐条交给回调。
/// 订阅事件流,逐条交给回调。`on_open` 在流接通的那一刻调一次:调用方据此
/// 分得清哪一次是重连 —— 断开的那一段里发生的事,流不会再说一遍。
///
/// 断开就返回 —— **重连由调用方决定**。守护那边已经有退避逻辑了,
/// 这里再来一套会变成两套互相不知道对方存在的重试。
pub async fn subscribe_events<F>(&self, mut on_event: F) -> Result<()>
pub async fn subscribe_events<O, F>(&self, on_open: O, mut on_event: F) -> Result<()>
where
O: FnOnce() + Send,
F: FnMut(tw_api::Event) + Send,
{
let stream = tokio::net::UnixStream::connect(&self.socket).await?;
Expand All @@ -1075,6 +1077,7 @@ impl ControlClient {
.header(hyper::header::ACCEPT, "text/event-stream")
.body(String::new())?;
let mut resp = sender.send_request(req).await?;
on_open();

let mut buf = String::new();
while let Some(frame) = resp.frame().await {
Expand Down
249 changes: 189 additions & 60 deletions src-tauri/src/lib.rs

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions src-tauri/src/notices/macos/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ impl Sink for NativeSink {
fn withdraw(&self, key: &str) {
un::withdraw(key);
}

fn announce(&self, key: &str, title: &str, body: &str) {
un::post(
key.to_string(),
title.to_string(),
body.to_string(),
thread_of(key),
false,
);
}
}

/// 同一种的归在一起:用键的种类(冒号前那段)做 thread
Expand Down
15 changes: 14 additions & 1 deletion src-tauri/src/notices/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,19 @@ impl Notices {
}
}

/// 告知一件事:**不是一个待处理的问题**,不进提醒列表,只弹一条系统通知。
///
/// 给那种窗口没开、而用户该知道一下的时刻用(第一次开机自启)。用户选了「只在
/// 应用内」或者关掉提醒的,就不弹 —— 那是他说了不要被打断。
pub fn announce(&self, key: &str, title: &str, body: &str) {
if self.mode() != Mode::System {
return;
}
for s in &self.sinks {
s.announce(key, title, body);
}
}

/// 走一遍那五关。
pub fn ingest(self: &Arc<Self>, signal: Signal, at_ms: u64) {
match signal.change {
Expand Down Expand Up @@ -596,7 +609,7 @@ pub fn take_pending_view() -> Option<String> {
PENDING_VIEW.lock().ok().and_then(|mut g| g.take())
}

fn now_ms() -> u64 {
pub fn now_ms() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
Expand Down
49 changes: 45 additions & 4 deletions src-tauri/src/notices/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,15 @@ pub fn from_event(ev: &Event) -> Vec<Signal> {
Event::QuotaExhausted {
provider,
window,
reset_in_secs,
resets_at_ms,
..
} => {
let reset = reset_in_secs.map(after).unwrap_or_default();
// core 给的是重置的时刻:按现在去数还有多久
let secs = resets_at_ms.map(|at| at.saturating_sub(super::now_ms()) / 1000);
let reset = secs.map(after).unwrap_or_default();
// 几分钟后就恢复的窗口不值得打断 —— 用户等一会儿就好了
let level = match reset_in_secs {
Some(s) if *s <= 300 => Level::Info,
let level = match secs {
Some(s) if s <= 300 => Level::Info,
_ => Level::Warning,
};
vec![
Expand Down Expand Up @@ -457,6 +459,24 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec<Signal> {
.now()
.suppressing(suppresses("gateway")),
],
// 程序本身运行不了:不会自己好,转发已经停了
CoreState::Failed { .. } => vec![
Signal::raised(
"gateway",
Level::Critical,
tr!("网关无法启动", "Gateway Cannot Start"),
)
.body(
tr!(
"core 程序未能运行,转发已停止。打开窗口可以查看原因并重试。",
"The core program could not run, so forwarding has stopped. Open the window to see why and try again."
)
.to_string(),
)
.view(SETTINGS)
.now()
.suppressing(suppresses("gateway")),
],
// 偶发崩溃自己好了就别打扰人;连着崩说明不是偶发
CoreState::Restarting { attempt, .. } if *attempt >= 3 => vec![
Signal::raised(
Expand All @@ -478,6 +498,27 @@ pub fn from_core_state(state: &crate::supervisor::CoreState) -> Vec<Signal> {
}
}

/// core 活着但不回心跳,被换掉了。
///
/// **只进应用内**:自己好了的一次卡顿和一次偶发崩溃一个待遇,不打断人。但那几秒里
/// 用户看到的失败要有地方说得清,所以留一条。同一件事再发生只累计次数
pub fn wedged() -> Signal {
Signal::raised(
"wedged",
Level::Info,
tr!("网关曾无响应,已重启", "Gateway Stopped Responding and Was Restarted"),
)
.body(
tr!(
"网关连续几次没有响应,已自动重启。重启期间的请求可能失败。",
"The gateway did not respond several times in a row and was restarted automatically. Requests during the restart may have failed."
)
.to_string(),
)
.view(SETTINGS)
.now()
}

/// `5h` / `weekly` → 「5 小时」「每周」(英文是 `5-hour`、`weekly`)。认不出来的原样用
fn window_label(w: &str) -> String {
match w {
Expand Down
14 changes: 14 additions & 0 deletions src-tauri/src/notices/sink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ pub trait Sink: Send + Sync {
fn withdraw(&self, _key: &str) {}
/// 现在开着的全部。界面按这一份重画
fn listed(&self, _all: &[Notice]) {}
/// 告知一件事(见 `Notices::announce`)。**只有系统通知这一端要做什么**:
/// 它不是一个待处理的问题,界面里的列表不收它
fn announce(&self, _key: &str, _title: &str, _body: &str) {}
}

/// 界面里的通知中心。**窗口关着时照样调**:内容在 Rust 这边留着,
Expand Down Expand Up @@ -79,4 +82,15 @@ impl Sink for SystemSink {
.body(&notice.body)
.show();
}

fn announce(&self, _key: &str, title: &str, body: &str) {
use tauri_plugin_notification::NotificationExt;
let _ = self
.app
.notification()
.builder()
.title(title)
.body(body)
.show();
}
}
45 changes: 40 additions & 5 deletions src-tauri/src/notices/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,14 +383,20 @@ fn only_an_edit_made_outside_the_app_is_reported() {
assert!(s[0].body.contains("第 4 行"), "{}", s[0].body);
}

/// `secs` 秒之后重置的那个时刻。**多给半秒**:规则拿到事件时按那一刻的时钟数,
/// 测试从造事件到读结果之间走掉的那几毫秒,不该让「2 小时」变成「1 小时 59 分」
fn resets_in(secs: u64) -> Option<u64> {
Some(super::now_ms() + secs * 1000 + 500)
}

#[test]
fn a_window_that_resets_in_a_moment_is_not_worth_interrupting() {
let quota = |secs: u64| {
rules::from_event(&tw_api::Event::QuotaExhausted {
id: 1,
provider: "chatgpt".into(),
window: "5h".into(),
reset_in_secs: Some(secs),
resets_at_ms: resets_in(secs),
at_ms: T0,
})[0]
.clone()
Expand All @@ -413,13 +419,13 @@ fn a_quota_report_below_the_limit_clears_that_window() {
tw_api::QuotaWindow {
window: "weekly".into(),
used_percent: 21.0,
reset_in_secs: None,
resets_at_ms: None,
status: None,
},
tw_api::QuotaWindow {
window: "5h".into(),
used_percent: 100.0,
reset_in_secs: Some(600),
resets_at_ms: resets_in(600),
status: Some("rejected".into()),
},
],
Expand Down Expand Up @@ -455,7 +461,7 @@ fn quota_exhausted(window: &str, reset_in_secs: Option<u64>) -> tw_api::Event {
id: 1,
provider: "chatgpt".into(),
window: window.into(),
reset_in_secs,
resets_at_ms: reset_in_secs.and_then(resets_in),
at_ms: T0,
}
}
Expand Down Expand Up @@ -557,13 +563,17 @@ fn in_english_no_rule_writes_a_chinese_word() {
attempt: 3,
in_ms: 1_000,
},
CoreState::Failed {
reason: "/Applications/ThinkWatch.app/twcore could not be run".into(),
},
];
with_lang(Lang::En, || {
let mut signals: Vec<Signal> = events.iter().flat_map(rules::from_event).collect();
signals.extend(states.iter().flat_map(rules::from_core_state));
signals.push(rules::wedged());
assert_eq!(
signals.len(),
events.len() + states.len(),
events.len() + states.len() + 1,
"每一件都该说一句"
);
for s in &signals {
Expand Down Expand Up @@ -722,3 +732,28 @@ fn a_listen_change_that_did_not_take_is_raised_and_one_that_did_clears_it() {
"换成了就收起来,不另发一条"
);
}

/// core 程序本身运行不了:**不会自己好**,转发已经停了 —— 和安全模式一样要打断人
#[test]
fn a_core_that_cannot_start_interrupts() {
use crate::supervisor::CoreState;
let s = rules::from_core_state(&CoreState::Failed {
reason: "无法运行 /x/twcore:No such file or directory (os error 2)".into(),
});
assert_eq!(s.len(), 1);
assert_eq!(s[0].key, "gateway");
assert_eq!(s[0].level, Level::Critical);
// 连上之后撤掉:和别的网关状态共用一个键
assert_eq!(
rules::from_core_state(&CoreState::Running { pid: 1 })[0].key,
"gateway"
);
}

/// core 卡住被换掉:自己好了的一次卡顿不打断人,只在应用内留一条
#[test]
fn a_wedged_core_that_was_replaced_is_recorded_without_interrupting() {
let s = rules::wedged();
assert_eq!(s.level, Level::Info);
assert!(!s.body.is_empty());
}
48 changes: 42 additions & 6 deletions src-tauri/src/supervisor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ pub enum CoreState {
SafeMode,
/// UI 主动停的,不再重启
Stopped,
/// 拉不起来:程序运行不了(找不到、没有执行权限、不是这台机器能跑的)。
///
/// **这不是「core 在崩」**,重启循环掩盖不了它,所以守护停下来等用户点重试。
/// 原因要带着:界面上只写「正在启动」的话,用户会一直等下去
Failed {
reason: String,
},
}

/// 一次 core 退出之后,守护循环下一步做什么。
Expand Down Expand Up @@ -139,10 +146,12 @@ impl Supervisor {
"Core is starting; try again in a moment"
))
}
CoreState::SafeMode | CoreState::Stopped => anyhow::bail!(tr!(
"core 未运行,无法重启",
"Core is not running and cannot be restarted"
)),
CoreState::SafeMode | CoreState::Stopped | CoreState::Failed { .. } => {
anyhow::bail!(tr!(
"core 未运行,无法重启",
"Core is not running and cannot be restarted"
))
}
};
self.intentional.store(true, Ordering::SeqCst);
// SIGTERM 而不是 SIGKILL:给它机会把 socket 和 lock 文件清掉。
Expand Down Expand Up @@ -218,11 +227,24 @@ impl Supervisor {
let args = self.command_args(safe);
let started = Instant::now();

let mut child = tokio::process::Command::new(&self.binary)
let spawned = tokio::process::Command::new(&self.binary)
.args(&args)
// core 的日志走它自己的 stderr;UI 侧只需要知道它活着。
.kill_on_drop(true)
.spawn()?;
.spawn();
let mut child = match spawned {
Ok(c) => c,
Err(e) => {
let path = self.binary.display();
self.set(CoreState::Failed {
reason: tr!(
format!("无法运行 {path}:{e}"),
format!("{path} could not be run: {e}")
),
});
return Err(e.into());
}
};

if let Some(pid) = child.id() {
self.set(CoreState::Running { pid });
Expand Down Expand Up @@ -300,6 +322,20 @@ mod tests {
)
}

/// 程序运行不了:**停在「无法启动」、带着原因**,不是停在「正在启动」。以前停在
/// 后者,界面上一直说「请稍候」,而这件事等多久都不会好。
#[tokio::test]
async fn a_binary_that_cannot_run_leaves_the_reason_in_the_state() {
let s = sup();
assert!(s.run_once(false).await.is_err());
match s.state() {
CoreState::Failed { reason } => {
assert!(reason.contains("/nonexistent/twcore"), "{reason}");
}
other => panic!("该是无法启动,实际 {other:?}"),
}
}

#[test]
fn the_command_always_carries_our_pid() {
// 「让用户认为他俩就是一个程序」的落点:UI 没了 core 跟着退。
Expand Down
Loading
Loading