chore: clippy 全部清乾淨,CI 有新警告就失敗;make lint
工程基礎計畫 E6。33 個警告改掉,行為不變(測試全過): - 順序一樣、寫法更直接:sort_by(b.cmp(a)) → sort_by_key(Reverse)(三處,都是穩定排序);chunks_exact(4) → as_chunks::<4>()(拿掉一個 unwrap);用 checked_div 取代先判斷 total > 0;兩個一樣的分支合成一個條件;計數迴圈用 enumerate;單一運算式的立即呼叫閉包改成區塊;回傳 () 的函式不再包在 Ok() 裡。 - 型別取名:VoicesAnswer、Vocab、Group。system_prompt 的 11 個參數留著(每個是指示的不同部分),標 allow 並寫理由。 - 小的:多餘的 clone、format!、vec!、into、借用;3_600_000 的分組;文件註解的縮排和空行;新檔案明說不截斷。 - .gitea/workflows/ci.yml:clippy 改成 `--all-targets -- -D warnings`(原本只報告)。make lint 跑一樣的檢查。 - 不加 rust-toolchain.toml:AnyBot 是使用者自己建的,釘版本會逼每個人和 make update-server 多下載一套 Rust;CI 映像本來就釘 1.98.1。 已驗證:cargo test 560 全過;cargo clippy --bin anybot --all-targets -- -D warnings 在這台 Mac 過。 未驗證:只在 Linux 編譯的程式(x11.rs、wl.rs、portal.rs…)的 clippy:這台 Mac 看不到,第一次 CI 跑會檢查,若有警告會擋下來。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1ad81532cd
commit
d23ca7628d
|
|
@ -1,5 +1,5 @@
|
||||||
# Every push and pull request: build, test, clippy (report only — the tree is not rustfmt'
|
# Every push and pull request: build, test, clippy with no warnings allowed (the tree is not
|
||||||
# clean, so `cargo fmt --check` would need its own one-time reformatting change first). Release builds are release.yml's job.
|
# rustfmt-clean, so `cargo fmt --check` would need its own one-time reformatting change first). Release builds are release.yml's job.
|
||||||
#
|
#
|
||||||
# Runners (see deploy/ci/README.md):
|
# Runners (see deploy/ci/README.md):
|
||||||
# anybot-linux a Linux computer with Docker; jobs run in anybot-builder:22.04
|
# anybot-linux a Linux computer with Docker; jobs run in anybot-builder:22.04
|
||||||
|
|
@ -31,8 +31,10 @@ jobs:
|
||||||
run: |
|
run: |
|
||||||
cargo test --bin anybot -- --skip live > "${RUNNER_TEMP:-/tmp}/test.log" 2>&1 || { tail -n 80 "${RUNNER_TEMP:-/tmp}/test.log"; exit 1; }
|
cargo test --bin anybot -- --skip live > "${RUNNER_TEMP:-/tmp}/test.log" 2>&1 || { tail -n 80 "${RUNNER_TEMP:-/tmp}/test.log"; exit 1; }
|
||||||
tail -n 5 "${RUNNER_TEMP:-/tmp}/test.log"
|
tail -n 5 "${RUNNER_TEMP:-/tmp}/test.log"
|
||||||
- name: Clippy (report only)
|
- name: Clippy (no warnings)
|
||||||
run: cargo clippy --bin anybot 2>&1 | tail -30
|
# The tree is clippy-clean (engineering plan E6): a new warning fails the build. Linux-only
|
||||||
|
# code (x11.rs, wl.rs, portal.rs…) is checked here first — it can't be on a Mac.
|
||||||
|
run: cargo clippy --bin anybot --all-targets -- -D warnings
|
||||||
- name: Relay build and test
|
- name: Relay build and test
|
||||||
run: cd relay && cargo test
|
run: cd relay && cargo test
|
||||||
|
|
||||||
|
|
|
||||||
5
Makefile
5
Makefile
|
|
@ -51,6 +51,7 @@ help:
|
||||||
@echo " make doctor 檢查這台缺什麼"
|
@echo " make doctor 檢查這台缺什麼"
|
||||||
@echo " make test 跑測試"
|
@echo " make test 跑測試"
|
||||||
@echo " make lint-sh 檢查 shell 腳本(語法、中文標點黏變數)"
|
@echo " make lint-sh 檢查 shell 腳本(語法、中文標點黏變數)"
|
||||||
|
@echo " make lint 跟 CI 一樣的 clippy 檢查(有警告就失敗)"
|
||||||
@echo ""
|
@echo ""
|
||||||
@echo " make serve 不開視窗執行(伺服器、一直開著的電腦)"
|
@echo " make serve 不開視窗執行(伺服器、一直開著的電腦)"
|
||||||
@echo " make setup 把這台接到你的 AnyBot(終端機裡的引導畫面)"
|
@echo " make setup 把這台接到你的 AnyBot(終端機裡的引導畫面)"
|
||||||
|
|
@ -94,6 +95,10 @@ test: check-rust
|
||||||
lint-sh:
|
lint-sh:
|
||||||
@sh deploy/ci/lint-sh.sh
|
@sh deploy/ci/lint-sh.sh
|
||||||
|
|
||||||
|
# The same clippy check CI runs: no warnings allowed (clippy.toml has AnyBot's own rules).
|
||||||
|
lint: check-rust
|
||||||
|
$(CARGO) clippy --bin anybot --all-targets -- -D warnings
|
||||||
|
|
||||||
deps:
|
deps:
|
||||||
sh ./install.sh deps
|
sh ./install.sh deps
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -33,8 +33,9 @@
|
||||||
- 做法:`net::agent(timeout)` 統一建 `ureq` 用戶端(信任的憑證、逾時、User-Agent);`clippy.toml` 用 `disallowed-methods` 擋其他地方自己建。連接器的伺服器和 shell 指令開在自己的 process group,停掉時整群一起停(npx/uvx 帶起來的子行程不再留著)。`mcp::call` 收停止訊號(按停止不用等 120 秒)。
|
- 做法:`net::agent(timeout)` 統一建 `ureq` 用戶端(信任的憑證、逾時、User-Agent);`clippy.toml` 用 `disallowed-methods` 擋其他地方自己建。連接器的伺服器和 shell 指令開在自己的 process group,停掉時整群一起停(npx/uvx 帶起來的子行程不再留著)。`mcp::call` 收停止訊號(按停止不用等 120 秒)。
|
||||||
- 做完:`cargo clippy` 對新的違規報錯;停掉連接器後 `pgrep` 找不到它的子行程;按停止一秒內連接器呼叫就結束。
|
- 做完:`cargo clippy` 對新的違規報錯;停掉連接器後 `pgrep` 找不到它的子行程;按停止一秒內連接器呼叫就結束。
|
||||||
|
|
||||||
### E6. clippy 全清、CI 擋新的警告、釘住工具鏈 ⬜
|
### E6. clippy 全清、CI 擋新的警告 ✅
|
||||||
- 做法:清掉現有 clippy 警告;`.gitea/workflows/ci.yml` 的 clippy 改成 `-D warnings`;加 `rust-toolchain.toml`。
|
- 做法:清掉現有 clippy 警告;`.gitea/workflows/ci.yml` 的 clippy 改成 `-D warnings`;`make lint` 跑同一個檢查。
|
||||||
|
- 不加 `rust-toolchain.toml`:AnyBot 是使用者自己從原始碼建的,釘住版本會逼每個人(和 `make update-server`)多下載一套 Rust;CI 的映像已經釘 1.98.1,Cargo.toml 的 rust-version 管最低版本。
|
||||||
- 做完:`cargo clippy --all-targets -- -D warnings` 過。
|
- 做完:`cargo clippy --all-targets -- -D warnings` 過。
|
||||||
|
|
||||||
### E7. 共用的假模型測試工具 ⬜
|
### E7. 共用的假模型測試工具 ⬜
|
||||||
|
|
|
||||||
|
|
@ -4304,9 +4304,9 @@ mod tests {
|
||||||
let model = std::env::var("ANYBOT_LIVE_MODEL").unwrap_or_else(|_| "husky".into());
|
let model = std::env::var("ANYBOT_LIVE_MODEL").unwrap_or_else(|_| "husky".into());
|
||||||
let own = crate::model::BOT_COMPUTER_NAME.to_string();
|
let own = crate::model::BOT_COMPUTER_NAME.to_string();
|
||||||
let _ = std::fs::remove_dir_all("/tmp/anybot-live");
|
let _ = std::fs::remove_dir_all("/tmp/anybot-live");
|
||||||
let mut specs = tools::specs_for(&[own.clone()], &own);
|
let mut specs = tools::specs_for(std::slice::from_ref(&own), &own);
|
||||||
if crate::botbrowser::available() {
|
if crate::botbrowser::available() {
|
||||||
specs.extend(crate::web::specs_for(&[own.clone()], &own));
|
specs.extend(crate::web::specs_for(std::slice::from_ref(&own), &own));
|
||||||
}
|
}
|
||||||
let job = Job {
|
let job = Job {
|
||||||
req: ChatRequest {
|
req: ChatRequest {
|
||||||
|
|
|
||||||
16
src/app.rs
16
src/app.rs
|
|
@ -382,10 +382,8 @@ impl App {
|
||||||
// ANYBOT_SHOT_PINS=n: the grid at the top shows n bots (the main one and n-1 pinned).
|
// ANYBOT_SHOT_PINS=n: the grid at the top shows n bots (the main one and n-1 pinned).
|
||||||
if let Some(n) = std::env::var("ANYBOT_SHOT_PINS").ok().and_then(|v| v.parse::<usize>().ok()) {
|
if let Some(n) = std::env::var("ANYBOT_SHOT_PINS").ok().and_then(|v| v.parse::<usize>().ok()) {
|
||||||
let primary = state.primary_bot;
|
let primary = state.primary_bot;
|
||||||
let mut kept = 1;
|
for (i, b) in state.bots.iter_mut().filter(|b| b.pinned && b.id != primary).enumerate() {
|
||||||
for b in state.bots.iter_mut().filter(|b| b.pinned && b.id != primary) {
|
b.pinned = i + 1 < n;
|
||||||
b.pinned = kept < n;
|
|
||||||
kept += 1;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
state.skills = crate::skills::BUILTIN_SKILLS
|
state.skills = crate::skills::BUILTIN_SKILLS
|
||||||
|
|
@ -891,8 +889,8 @@ impl App {
|
||||||
j(serde_json::json!({"id": "1", "name": "第三季報表.xlsx", "bytes": 48_211_000, "from": "MacBook Pro", "to": "m", "to_name": "Mac mini", "state": "sending", "sent": 30_100_000, "at": now})),
|
j(serde_json::json!({"id": "1", "name": "第三季報表.xlsx", "bytes": 48_211_000, "from": "MacBook Pro", "to": "m", "to_name": "Mac mini", "state": "sending", "sent": 30_100_000, "at": now})),
|
||||||
j(serde_json::json!({"id": "2", "name": "IMG_2041.heic", "bytes": 3_420_000, "from": "手機", "to": "x", "to_name": "MacBook Pro", "state": "done", "at": now - 9 * 60_000})),
|
j(serde_json::json!({"id": "2", "name": "IMG_2041.heic", "bytes": 3_420_000, "from": "手機", "to": "x", "to_name": "MacBook Pro", "state": "done", "at": now - 9 * 60_000})),
|
||||||
j(serde_json::json!({"id": "3", "name": "https://thsrc.com.tw/booking/…", "bytes": 60, "text": "https://thsrc.com.tw/booking/abc", "from": "MacBook Pro", "to": "phone", "to_name": "手機", "state": "ready", "at": now - 40 * 60_000})),
|
j(serde_json::json!({"id": "3", "name": "https://thsrc.com.tw/booking/…", "bytes": 60, "text": "https://thsrc.com.tw/booking/abc", "from": "MacBook Pro", "to": "phone", "to_name": "手機", "state": "ready", "at": now - 40 * 60_000})),
|
||||||
j(serde_json::json!({"id": "4", "name": "備份-2026-11.zip", "bytes": 812_000_000, "from": "MacBook Pro", "to": "l", "to_name": "客廳 Linux", "state": "waiting", "note": "目前離線", "at": now - 3 * 3600_000})),
|
j(serde_json::json!({"id": "4", "name": "備份-2026-11.zip", "bytes": 812_000_000, "from": "MacBook Pro", "to": "l", "to_name": "客廳 Linux", "state": "waiting", "note": "目前離線", "at": now - 3 * 3_600_000})),
|
||||||
j(serde_json::json!({"id": "5", "name": "合約草稿.pdf", "bytes": 1_250_000, "from": "研究助理", "to": "m", "to_name": "Mac mini", "state": "failed", "note": "那台電腦的磁碟滿了", "at": now - 26 * 3600_000})),
|
j(serde_json::json!({"id": "5", "name": "合約草稿.pdf", "bytes": 1_250_000, "from": "研究助理", "to": "m", "to_name": "Mac mini", "state": "failed", "note": "那台電腦的磁碟滿了", "at": now - 26 * 3_600_000})),
|
||||||
],
|
],
|
||||||
"x",
|
"x",
|
||||||
"m",
|
"m",
|
||||||
|
|
@ -3109,7 +3107,7 @@ impl App {
|
||||||
self.settle(id, TurnOutcome::Error);
|
self.settle(id, TurnOutcome::Error);
|
||||||
if let Some(m) = self.state.bot_mut(id).and_then(|b| b.messages.last_mut()).filter(|m| m.role == Role::Assistant) {
|
if let Some(m) = self.state.bot_mut(id).and_then(|b| b.messages.last_mut()).filter(|m| m.role == Role::Assistant) {
|
||||||
if m.text.is_empty() {
|
if m.text.is_empty() {
|
||||||
m.text = msg.into();
|
m.text = msg;
|
||||||
} else {
|
} else {
|
||||||
m.text.push_str(&format!("\n\n{msg}"));
|
m.text.push_str(&format!("\n\n{msg}"));
|
||||||
}
|
}
|
||||||
|
|
@ -6824,6 +6822,8 @@ fn unattended_what(msgs: &[Message]) -> &'static str {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// (Eleven inputs, each a different part of the instructions; a struct of them would only rename them.)
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_computer: &str, roles: &tools::Roles, missing: Option<&str>, lines: &[String], mac_apps: bool, mcp: bool, pinned: &[String], about_you: &[String]) -> String {
|
fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_computer: &str, roles: &tools::Roles, missing: Option<&str>, lines: &[String], mac_apps: bool, mcp: bool, pinned: &[String], about_you: &[String]) -> String {
|
||||||
use crate::profile::has;
|
use crate::profile::has;
|
||||||
// 能力: the rules for what this bot can do only (profile.rs); the rest isn't its business.
|
// 能力: the rules for what this bot can do only (profile.rs); the rest isn't its business.
|
||||||
|
|
@ -7508,7 +7508,7 @@ mod tests {
|
||||||
let h2 = group_history(&msgs, None, 0, &st);
|
let h2 = group_history(&msgs, None, 0, &st);
|
||||||
assert_eq!(sys1, sys2, "the instructions are the same from turn to turn");
|
assert_eq!(sys1, sys2, "the instructions are the same from turn to turn");
|
||||||
assert!(!sys1.contains("現在是") && sys1.contains("- 咖啡不加糖") && sys1.contains("search_memory"));
|
assert!(!sys1.contains("現在是") && sys1.contains("- 咖啡不加糖") && sys1.contains("search_memory"));
|
||||||
let view = |h: &[Message]| h.iter().map(|m| (m.role.clone(), m.text.clone(), m.context.clone())).collect::<Vec<_>>();
|
let view = |h: &[Message]| h.iter().map(|m| (m.role, m.text.clone(), m.context.clone())).collect::<Vec<_>>();
|
||||||
assert_eq!(view(&h2[..h1.len()]), view(&h1), "the first turn is the beginning of the second, word for word");
|
assert_eq!(view(&h2[..h1.len()]), view(&h1), "the first turn is the beginning of the second, word for word");
|
||||||
assert_eq!(h1[0].context, "〔送出時間:2025-11-11(週二)10:00〕\n〔相關記憶(AnyBot 依這則訊息找出來的,不一定都用得上):\n- 我喜歡靠窗的座位〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕");
|
assert_eq!(h1[0].context, "〔送出時間:2025-11-11(週二)10:00〕\n〔相關記憶(AnyBot 依這則訊息找出來的,不一定都用得上):\n- 我喜歡靠窗的座位〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕");
|
||||||
assert_eq!(h2[2].context, "〔送出時間:2025-11-11(週二)11:00〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕");
|
assert_eq!(h2[2].context, "〔送出時間:2025-11-11(週二)11:00〕\n〔用繁體中文和台灣用語回答,不要用簡體字〕");
|
||||||
|
|
|
||||||
|
|
@ -113,7 +113,7 @@ impl App {
|
||||||
}
|
}
|
||||||
// Words the person sent here are for pasting: the newest goes on the clipboard.
|
// Words the person sent here are for pasting: the newest goes on the clipboard.
|
||||||
if let Some(r) = fresh.iter().rev().find(|r| !r.text.is_empty()) {
|
if let Some(r) = fresh.iter().rev().find(|r| !r.text.is_empty()) {
|
||||||
crate::platform::copy_text(&ctx, &r.text);
|
crate::platform::copy_text(ctx, &r.text);
|
||||||
}
|
}
|
||||||
if !self.headless && self.state.alert_sound {
|
if !self.headless && self.state.alert_sound {
|
||||||
crate::voice::chime();
|
crate::voice::chime();
|
||||||
|
|
@ -207,7 +207,7 @@ impl App {
|
||||||
for (what, id) in acts {
|
for (what, id) in acts {
|
||||||
match what {
|
match what {
|
||||||
"reveal" => crate::preview::reveal(std::path::Path::new(&id)),
|
"reveal" => crate::preview::reveal(std::path::Path::new(&id)),
|
||||||
"copy" => crate::platform::copy_text(&ctx, &id),
|
"copy" => crate::platform::copy_text(ctx, &id),
|
||||||
"pick" => {
|
"pick" => {
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
pg.picked = Some(rx);
|
pg.picked = Some(rx);
|
||||||
|
|
|
||||||
|
|
@ -197,7 +197,7 @@ fn scenes() -> Vec<(&'static str, Open)> {
|
||||||
b.messages.push(Message::tool_result("audit-p1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[])));
|
b.messages.push(Message::tool_result("audit-p1", crate::plan::SUBMIT_TOOL, &crate::plan::approved_result(&[])));
|
||||||
b.messages.push(Message { tool_calls: vec![call("audit-p2", "新版:")], ..Message::assistant("", "模型") });
|
b.messages.push(Message { tool_calls: vec![call("audit-p2", "新版:")], ..Message::assistant("", "模型") });
|
||||||
b.plan = Some(crate::plan::Plan { task: long.into(), since: 0, stage: crate::plan::Stage::Doing, revisions: 0, steps: vec![
|
b.plan = Some(crate::plan::Plan { task: long.into(), since: 0, stage: crate::plan::Stage::Doing, revisions: 0, steps: vec![
|
||||||
crate::plan::Step { title: format!("備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND"), status: crate::plan::Status::Done },
|
crate::plan::Step { title: "備份舊資料夾到 /Volumes/Backup/very/deep/path/that/keeps/going/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaEND".into(), status: crate::plan::Status::Done },
|
||||||
crate::plan::Step { title: long.into(), status: crate::plan::Status::InProgress },
|
crate::plan::Step { title: long.into(), status: crate::plan::Status::InProgress },
|
||||||
crate::plan::Step { title: "檢查兩邊的檔案數量".into(), status: crate::plan::Status::Pending }] });
|
crate::plan::Step { title: "檢查兩邊的檔案數量".into(), status: crate::plan::Status::Pending }] });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -72,7 +72,7 @@ pub struct VoiceUi {
|
||||||
test_note: Arc<Mutex<Option<String>>>,
|
test_note: Arc<Mutex<Option<String>>>,
|
||||||
test_note_at: String,
|
test_note_at: String,
|
||||||
/// The voices 說 offers: fetched the first time a 聲音 menu opens, kept until 說 changes.
|
/// The voices 說 offers: fetched the first time a 聲音 menu opens, kept until 說 changes.
|
||||||
voices_rx: Option<Receiver<Result<Vec<(String, String)>, String>>>,
|
voices_rx: Option<Receiver<VoicesAnswer>>,
|
||||||
voice_list: Vec<(String, String)>,
|
voice_list: Vec<(String, String)>,
|
||||||
voices_err: String,
|
voices_err: String,
|
||||||
/// Which 說 (service, address, key) the list is for.
|
/// Which 說 (service, address, key) the list is for.
|
||||||
|
|
@ -84,6 +84,9 @@ pub struct VoiceUi {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a 聲音 row shows and offers.
|
/// What a 聲音 row shows and offers.
|
||||||
|
/// The voices a 說 service offers (id, name), or why not.
|
||||||
|
type VoicesAnswer = Result<Vec<(String, String)>, String>;
|
||||||
|
|
||||||
pub(super) struct VoiceRow {
|
pub(super) struct VoiceRow {
|
||||||
/// The chosen voice by name, or what an empty choice means.
|
/// The chosen voice by name, or what an empty choice means.
|
||||||
pub(super) shown: String,
|
pub(super) shown: String,
|
||||||
|
|
|
||||||
|
|
@ -1488,7 +1488,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let url = format!("http://127.0.0.1:{port}/");
|
let url = format!("http://127.0.0.1:{port}/");
|
||||||
let r = (|| -> Result<(), String> {
|
let r = {
|
||||||
botbrowser::as_job("lines", || -> Result<(), String> {
|
botbrowser::as_job("lines", || -> Result<(), String> {
|
||||||
botbrowser::open(&url, None)?;
|
botbrowser::open(&url, None)?;
|
||||||
let refs = || -> Result<String, String> { run("browser_elements", &json!({})).map(|r| r.0) };
|
let refs = || -> Result<String, String> { run("browser_elements", &json!({})).map(|r| r.0) };
|
||||||
|
|
@ -1509,7 +1509,7 @@ mod tests {
|
||||||
assert!(typed.contains("甲 ⏎ 乙"), "{typed}");
|
assert!(typed.contains("甲 ⏎ 乙"), "{typed}");
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
})();
|
};
|
||||||
let _ = botbrowser::quit(None);
|
let _ = botbrowser::quit(None);
|
||||||
r.unwrap();
|
r.unwrap();
|
||||||
}
|
}
|
||||||
|
|
@ -1552,7 +1552,7 @@ document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let url = format!("http://127.0.0.1:{port}/");
|
let url = format!("http://127.0.0.1:{port}/");
|
||||||
let r = (|| -> Result<(), String> {
|
let r = {
|
||||||
botbrowser::as_job("send", || -> Result<(), String> {
|
botbrowser::as_job("send", || -> Result<(), String> {
|
||||||
botbrowser::open(&url, None)?;
|
botbrowser::open(&url, None)?;
|
||||||
let info = |mode: &str, rf: &str, value: &str| -> Result<Value, String> { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) };
|
let info = |mode: &str, rf: &str, value: &str| -> Result<Value, String> { run(SEND_INFO, &json!({"mode": mode, "ref": rf, "value": value})).map(|r| serde_json::from_str(&r.0).unwrap()) };
|
||||||
|
|
@ -1589,7 +1589,7 @@ document.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey
|
||||||
assert_eq!((s["kind"].clone(), s["text"].clone()), (json!("search"), json!("貓抓板")), "{s}");
|
assert_eq!((s["kind"].clone(), s["text"].clone()), (json!("search"), json!("貓抓板")), "{s}");
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
})();
|
};
|
||||||
let _ = botbrowser::quit(None);
|
let _ = botbrowser::quit(None);
|
||||||
r.unwrap();
|
r.unwrap();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -387,7 +387,10 @@ impl Office {
|
||||||
}
|
}
|
||||||
self.set(&p.id, |p| p.state = "sending".into());
|
self.set(&p.id, |p| p.state = "sending".into());
|
||||||
let outcome = if p.to == me {
|
let outcome = if p.to == me {
|
||||||
let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else { Ok(self.land_text(&p.text, &p.id, &p.from)) };
|
let r = if p.text.is_empty() { self.land_file(&self.bin(&p.id), &p.name, &p.id, &p.from, p.bytes).map(|_| ()) } else {
|
||||||
|
self.land_text(&p.text, &p.id, &p.from);
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
match r {
|
match r {
|
||||||
Ok(()) => Outcome::Done,
|
Ok(()) => Outcome::Done,
|
||||||
Err(e) => Outcome::Failed(e),
|
Err(e) => Outcome::Failed(e),
|
||||||
|
|
|
||||||
|
|
@ -142,8 +142,8 @@ pub fn status() -> String {
|
||||||
},
|
},
|
||||||
Engine::Local if FETCHING.load(Ordering::Relaxed) => {
|
Engine::Local if FETCHING.load(Ordering::Relaxed) => {
|
||||||
let (got, total) = (GOT.load(Ordering::Relaxed), TOTAL.load(Ordering::Relaxed));
|
let (got, total) = (GOT.load(Ordering::Relaxed), TOTAL.load(Ordering::Relaxed));
|
||||||
if total > 0 {
|
if let Some(pct) = (got * 100).checked_div(total) {
|
||||||
format!("正在下載本機模型:{}%({} / {} MB),好了會自己開始", got * 100 / total, got >> 20, total >> 20)
|
format!("正在下載本機模型:{pct}%({} / {} MB),好了會自己開始", got >> 20, total >> 20)
|
||||||
} else {
|
} else {
|
||||||
"正在下載本機模型…".into()
|
"正在下載本機模型…".into()
|
||||||
}
|
}
|
||||||
|
|
@ -355,7 +355,7 @@ pub fn f32s_to_blob(v: &[f32]) -> Vec<u8> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn blob_to_f32s(b: &[u8]) -> Vec<f32> {
|
pub fn blob_to_f32s(b: &[u8]) -> Vec<f32> {
|
||||||
b.chunks_exact(4).map(|c| f32::from_le_bytes(c.try_into().unwrap())).collect()
|
b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cosine, with the guards a shelf of half-filled vectors deserves.
|
/// Cosine, with the guards a shelf of half-filled vectors deserves.
|
||||||
|
|
@ -383,7 +383,7 @@ mod tests {
|
||||||
// with words.
|
// with words.
|
||||||
configure("http://127.0.0.1:1/v1", "ollama");
|
configure("http://127.0.0.1:1/v1", "ollama");
|
||||||
assert!(!enabled(), "a port with nothing behind it means no semantic search");
|
assert!(!enabled(), "a port with nothing behind it means no semantic search");
|
||||||
assert!(embed(&vec!["test".to_string()]).is_none());
|
assert!(embed(&["test".to_string()]).is_none());
|
||||||
configure("http://127.0.0.1:11434", "off");
|
configure("http://127.0.0.1:11434", "off");
|
||||||
assert!(!enabled());
|
assert!(!enabled());
|
||||||
configure("http://127.0.0.1:11434", "");
|
configure("http://127.0.0.1:11434", "");
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,7 @@ pub fn search(bots: &[Bot], query: &str) -> (Vec<Hit>, bool) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Newest first; messages without a time keep their order, after the dated ones.
|
// Newest first; messages without a time keep their order, after the dated ones.
|
||||||
out.sort_by(|a, b| b.at.cmp(&a.at));
|
out.sort_by_key(|a| std::cmp::Reverse(a.at));
|
||||||
let more = out.len() > LIMIT;
|
let more = out.len() > LIMIT;
|
||||||
out.truncate(LIMIT);
|
out.truncate(LIMIT);
|
||||||
(out, more)
|
(out, more)
|
||||||
|
|
|
||||||
|
|
@ -53,7 +53,7 @@ impl Model {
|
||||||
if table.len() != rows * dim + rows * 4 {
|
if table.len() != rows * dim + rows * 4 {
|
||||||
return Err("模型檔大小不對(下載沒有完成?)".into());
|
return Err("模型檔大小不對(下載沒有完成?)".into());
|
||||||
}
|
}
|
||||||
let scales: Vec<f32> = table[rows * dim..].chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
let scales: Vec<f32> = table[rows * dim..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect();
|
||||||
table.truncate(rows * dim);
|
table.truncate(rows * dim);
|
||||||
table.shrink_to_fit();
|
table.shrink_to_fit();
|
||||||
let raw = std::fs::read(dir.join("vocab.bin")).map_err(|e| e.to_string())?;
|
let raw = std::fs::read(dir.join("vocab.bin")).map_err(|e| e.to_string())?;
|
||||||
|
|
@ -179,7 +179,10 @@ pub fn normalize(text: &str) -> String {
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_vocab(raw: &[u8]) -> Result<(HashMap<Box<str>, u32>, Vec<f32>, usize), String> {
|
/// The words and their rows, the per-row scales, and the vector size.
|
||||||
|
type Vocab = (HashMap<Box<str>, u32>, Vec<f32>, usize);
|
||||||
|
|
||||||
|
fn read_vocab(raw: &[u8]) -> Result<Vocab, String> {
|
||||||
if raw.len() < 8 || &raw[..4] != b"AVB1" {
|
if raw.len() < 8 || &raw[..4] != b"AVB1" {
|
||||||
return Err("字表檔格式不對".into());
|
return Err("字表檔格式不對".into());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1542,11 +1542,10 @@ for line in sys.stdin:
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and
|
/// Live integration with the openapi-mcp (Go) server, which hot-reloads its swagger and
|
||||||
/// shouts list_changed over the SSE stream. Setup:
|
/// shouts list_changed over the SSE stream. Setup: /tmp/openapimcp-live.yaml exists (port 3901,
|
||||||
/// 1. /tmp/openapimcp-live.yaml exists (port 3901, Spec.File /tmp/openapimcp-live.json,
|
/// Spec.File /tmp/openapimcp-live.json, ReloadSeconds 60 so only the management endpoint
|
||||||
/// ReloadSeconds 60 so only the management endpoint reloads — the openapimcp repo ships one),
|
/// reloads — the openapimcp repo ships one); from the openapimcp repo run
|
||||||
/// 2. from the openapimcp repo: ./bin/srv -f /tmp/openapimcp-live.yaml
|
/// `./bin/srv -f /tmp/openapimcp-live.yaml`; then `cargo test openapimcp_live -- --ignored --nocapture`.
|
||||||
/// Then: cargo test openapimcp_live -- --ignored --nocapture
|
|
||||||
/// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE
|
/// Adding a path to the spec file and POSTing /api/reload must reach us over the open SSE
|
||||||
/// stream and refresh the tools without a reconnect.
|
/// stream and refresh the tools without a reconnect.
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -83,10 +83,10 @@ pub const TEMPLATES: [Template; 5] = [
|
||||||
Template { name: "開發助手", description: "看程式、跑測試、追 GitHub 上的事", instructions: "改程式前先讀相關檔案和測試。每次修改後跑測試,回報結果。PR 或 CI 的事件來時,先看紀錄再下結論。", shape: "hex", color: "black" },
|
Template { name: "開發助手", description: "看程式、跑測試、追 GitHub 上的事", instructions: "改程式前先讀相關檔案和測試。每次修改後跑測試,回報結果。PR 或 CI 的事件來時,先看紀錄再下結論。", shape: "hex", color: "black" },
|
||||||
];
|
];
|
||||||
|
|
||||||
/// ---- Skill files (P7): a skill you can keep in a file, share, and install ----
|
// ---- Skill files (P7): a skill you can keep in a file, share, and install ----
|
||||||
///
|
//
|
||||||
/// A `.md` file in `<data>/skills/`: front matter (`name:`, `description:`), the instructions
|
// A `.md` file in `<data>/skills/`: front matter (`name:`, `description:`), the instructions
|
||||||
/// as the body, and an optional ```steps fence (the ReplayStep list a replay follows).
|
// as the body, and an optional ```steps fence (the ReplayStep list a replay follows).
|
||||||
|
|
||||||
pub fn skill_dir() -> std::path::PathBuf {
|
pub fn skill_dir() -> std::path::PathBuf {
|
||||||
// Tests never touch the person's data folder.
|
// Tests never touch the person's data folder.
|
||||||
|
|
@ -214,11 +214,9 @@ pub fn skillify(prompt: &str, recs: &[crate::oplog::Record]) -> Option<Skill> {
|
||||||
done.push((call_id.clone(), true));
|
done.push((call_id.clone(), true));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op => {
|
crate::oplog::Record::ToolFinished { op: o, call_id, status, .. } if o == &op && status != "done" => {
|
||||||
if status != "done" {
|
if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) {
|
||||||
if let Some(e) = done.iter_mut().find(|(c, _)| c == call_id) {
|
e.1 = false;
|
||||||
e.1 = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
|
|
|
||||||
|
|
@ -323,9 +323,8 @@ pub fn search_as(bot: u64, query: &str, kinds: &[&str], limit: usize, literal: b
|
||||||
if !have.contains(t.as_str()) {
|
if !have.contains(t.as_str()) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if *f >= 1.0 {
|
// (A whole term, or a piece no matched whole term already counts.)
|
||||||
got += w;
|
if *f >= 1.0 || !terms.iter().any(|(big, bf)| *bf >= 1.0 && big.contains(t.as_str()) && have.contains(big.as_str())) {
|
||||||
} else if !terms.iter().any(|(big, bf)| *bf >= 1.0 && big.contains(t.as_str()) && have.contains(big.as_str())) {
|
|
||||||
got += w;
|
got += w;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -675,7 +674,9 @@ const FOLD_CHARS: usize = 400;
|
||||||
fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String {
|
fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String {
|
||||||
let asks: Vec<String> = items.iter().map(|(a, _)| a.replace('、', ",")).collect();
|
let asks: Vec<String> = items.iter().map(|(a, _)| a.replace('、', ",")).collect();
|
||||||
let vecs: Option<Vec<Vec<f32>>> = if crate::embed::enabled() { crate::embed::embed(&asks) } else { None };
|
let vecs: Option<Vec<Vec<f32>>> = if crate::embed::enabled() { crate::embed::embed(&asks) } else { None };
|
||||||
let mut groups: Vec<(String, HashSet<String>, Option<Vec<f32>>, u32)> = vec![];
|
// (the ask, its words, its vector, how many asked it)
|
||||||
|
type Group = (String, HashSet<String>, Option<Vec<f32>>, u32);
|
||||||
|
let mut groups: Vec<Group> = vec![];
|
||||||
for (i, ask) in asks.iter().enumerate() {
|
for (i, ask) in asks.iter().enumerate() {
|
||||||
if ask.is_empty() {
|
if ask.is_empty() {
|
||||||
continue;
|
continue;
|
||||||
|
|
@ -691,7 +692,7 @@ fn fold_line(label: &str, items: &[(String, u32)], total: u32) -> String {
|
||||||
None => groups.push((ask.clone(), ws, v, n)),
|
None => groups.push((ask.clone(), ws, v, n)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
groups.sort_by(|a, b| b.3.cmp(&a.3));
|
groups.sort_by_key(|a| std::cmp::Reverse(a.3));
|
||||||
let mut s = format!("{label}({total} 件):");
|
let mut s = format!("{label}({total} 件):");
|
||||||
let mut shown = 0u32;
|
let mut shown = 0u32;
|
||||||
for (i, (ask, _, _, n)) in groups.iter().enumerate() {
|
for (i, (ask, _, _, n)) in groups.iter().enumerate() {
|
||||||
|
|
|
||||||
|
|
@ -60,7 +60,7 @@ fn connect(p: &std::path::Path) -> Option<Connection> {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if !p.exists() {
|
if !p.exists() {
|
||||||
use std::os::unix::fs::OpenOptionsExt;
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
let _ = std::fs::OpenOptions::new().write(true).create(true).mode(0o600).open(p);
|
let _ = std::fs::OpenOptions::new().write(true).create(true).truncate(false).mode(0o600).open(p);
|
||||||
}
|
}
|
||||||
let c = Connection::open(p).ok()?;
|
let c = Connection::open(p).ok()?;
|
||||||
crate::httpd::tighten_permissions(p);
|
crate::httpd::tighten_permissions(p);
|
||||||
|
|
@ -679,7 +679,7 @@ pub fn docs_search(query: &str, limit: usize) -> Vec<(String, String)> {
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
scored.sort_by(|a, b| b.0.cmp(&a.0));
|
scored.sort_by_key(|a| std::cmp::Reverse(a.0));
|
||||||
for (_, path, text) in scored {
|
for (_, path, text) in scored {
|
||||||
if !words.iter().any(|(p, t)| p == &path && t == &text) {
|
if !words.iter().any(|(p, t)| p == &path && t == &text) {
|
||||||
words.push((path, text));
|
words.push((path, text));
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue