版本: v<number>-<commit> with the build time, the same in the app, the phone, --version and the server log

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
王性驊 2026-11-11 13:51:52 +08:00
parent 36bc2bedaa
commit 9d6b346462
11 changed files with 136 additions and 26 deletions

2
Cargo.lock generated
View File

@ -336,7 +336,7 @@ dependencies = [
[[package]] [[package]]
name = "anybot" name = "anybot"
version = "0.1.0" version = "0.0.1"
dependencies = [ dependencies = [
"agent-desktop-core", "agent-desktop-core",
"agent-desktop-linux", "agent-desktop-linux",

View File

@ -1,6 +1,6 @@
[package] [package]
name = "anybot" name = "anybot"
version = "0.1.0" version = "0.0.1"
license = "Apache-2.0" license = "Apache-2.0"
edition = "2021" edition = "2021"
# Older Rust stops with a clear message instead of odd errors deep in a dependency. # Older Rust stops with a clear message instead of odd errors deep in a dependency.

View File

@ -11,10 +11,14 @@
export PATH := $(HOME)/.cargo/bin:$(PATH) export PATH := $(HOME)/.cargo/bin:$(PATH)
CARGO ?= cargo CARGO ?= cargo
UNAME := $(shell uname -s) UNAME := $(shell uname -s)
# `git describe` prints nothing outside a repo; sed passes the empty string through with # The version, as the program shows it: v<number in Cargo.toml>-<commit>, with "-dirty" when what
# status 0, so "|| echo dev" never fired and VERSION came out blank ("AnyBot ", dist files # goes into the program has uncommitted changes (the same paths as INPUTS in build.rs). Outside git
# named ".tar.gz"). grep . fails on empty input, which makes the fallback work. # it is just v<number>. ANYBOT_GIT_COMMIT is handed to cargo, so the program built here and the
VERSION ?= $(shell git describe --tags --always 2>/dev/null | sed 's/^v//' | grep . || echo dev) # dist file names say the same thing (build.rs takes it instead of asking git again).
VERSION_NUMBER := $(shell sed -n 's/^version *= *"\(.*\)"/\1/p' Cargo.toml | head -n 1)
GIT_COMMIT := $(shell git rev-parse --short=7 HEAD 2>/dev/null)$(shell git status --porcelain --untracked-files=no -- src box fonts icons mobile Cargo.toml Cargo.lock build.rs 2>/dev/null | grep -q . && echo -dirty)
export ANYBOT_GIT_COMMIT ?= $(GIT_COMMIT)
VERSION ?= v$(VERSION_NUMBER)$(if $(ANYBOT_GIT_COMMIT),-$(ANYBOT_GIT_COMMIT))
TARGET := $(or $(CARGO_TARGET_DIR),target) TARGET := $(or $(CARGO_TARGET_DIR),target)
APPDIR ?= $(HOME)/Applications APPDIR ?= $(HOME)/Applications
BIN := $(TARGET)/release/anybot BIN := $(TARGET)/release/anybot

58
build.rs Normal file
View File

@ -0,0 +1,58 @@
// Which build this is, for 設定 › 更新, the phone and `anybot --version`: v<version>-<commit>.
//
// v0.0.1-36bc2be built from commit 36bc2be as it is
// v0.0.1-36bc2be-dirty built from 36bc2be with changes to what goes into the program
// v0.0.1 no git here (a source tarball)
//
// <version> is the one in Cargo.toml, the only place the number is kept. The commit comes from
// ANYBOT_GIT_COMMIT when it is set (make sets it, so the program and the dist file names agree),
// otherwise from git. The build time is not baked in: it is the program file's own time (src/version.rs).
use std::process::Command;
/// What goes into the program: a change anywhere else (docs, deploy scripts) doesn't make it "dirty".
const INPUTS: &[&str] = &["src", "box", "fonts", "icons", "mobile", "Cargo.toml", "Cargo.lock", "build.rs"];
fn git(args: &[&str]) -> Option<String> {
let out = Command::new("git").args(args).output().ok()?;
if !out.status.success() {
return None;
}
let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
(!s.is_empty()).then_some(s)
}
fn main() {
let number = std::env::var("CARGO_PKG_VERSION").unwrap_or_default();
let commit = match std::env::var("ANYBOT_GIT_COMMIT").ok().filter(|s| !s.trim().is_empty()) {
Some(c) => Some(c.trim().to_string()),
None => git(&["rev-parse", "--short=7", "HEAD"]).map(|c| {
let mut args = vec!["status", "--porcelain", "--untracked-files=no", "--"];
args.extend_from_slice(INPUTS);
let dirty = git(&args).is_some();
if dirty { format!("{c}-dirty") } else { c }
}),
};
let label = match commit {
Some(c) => format!("v{number}-{c}"),
None => format!("v{number}"),
};
println!("cargo:rustc-env=ANYBOT_VERSION={label}");
// Run again when the commit changes (commit, checkout, pull) or what goes into the program
// does (then it's compiled again anyway). Not on the index: `git status` rewrites it, and every
// rerun recompiles the whole program.
println!("cargo:rerun-if-env-changed=ANYBOT_GIT_COMMIT");
for p in INPUTS {
println!("cargo:rerun-if-changed={p}");
}
if let Some(dir) = git(&["rev-parse", "--absolute-git-dir"]) {
println!("cargo:rerun-if-changed={dir}/HEAD");
}
if let Some(common) = git(&["rev-parse", "--path-format=absolute", "--git-common-dir"]) {
for p in ["refs/heads", "packed-refs"] {
if std::path::Path::new(&common).join(p).exists() {
println!("cargo:rerun-if-changed={common}/{p}");
}
}
}
}

View File

@ -1,10 +1,13 @@
#!/bin/sh #!/bin/sh
# Make AnyBot.app from the release build and zip it (run from app/ on a Mac, after # Make AnyBot.app from the release build and zip it (run from app/ on a Mac, after
# `cargo build --release`): deploy/mac/bundle.sh 1.2.0 → dist/AnyBot-1.2.0-macos-<arch>.zip # `cargo build --release`): deploy/mac/bundle.sh v0.0.1-36bc2be → dist/AnyBot-v0.0.1-36bc2be-macos-<arch>.zip
# With KEEP_APP=1 it leaves dist/AnyBot.app instead of zipping it (make install). # With KEEP_APP=1 it leaves dist/AnyBot.app instead of zipping it (make install).
# Signed with this Mac's own fixed key (no Apple developer account): the first time, right-click › 打開. # Signed with this Mac's own fixed key (no Apple developer account): the first time, right-click › 打開.
set -e set -e
VERSION=${1:?version} VERSION=${1:?version}
# Info.plist wants plain numbers (0.0.1): the commit stays in the file name and in the app itself.
NUMBER=$(printf '%s' "$VERSION" | sed -n 's/^v\{0,1\}\([0-9][0-9.]*\).*/\1/p')
NUMBER=${NUMBER:-0.0.0}
BIN=${CARGO_TARGET_DIR:-target}/release/anybot BIN=${CARGO_TARGET_DIR:-target}/release/anybot
ARCH=$(uname -m) ARCH=$(uname -m)
OUT=dist OUT=dist
@ -31,8 +34,8 @@ cat > "$APP/Contents/Info.plist" <<PLIST
<key>CFBundleExecutable</key><string>AnyBot</string> <key>CFBundleExecutable</key><string>AnyBot</string>
<key>CFBundleIconFile</key><string>AnyBot</string> <key>CFBundleIconFile</key><string>AnyBot</string>
<key>CFBundlePackageType</key><string>APPL</string> <key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>$VERSION</string> <key>CFBundleShortVersionString</key><string>$NUMBER</string>
<key>CFBundleVersion</key><string>$VERSION</string> <key>CFBundleVersion</key><string>$NUMBER</string>
<key>LSMinimumSystemVersion</key><string>12.0</string> <key>LSMinimumSystemVersion</key><string>12.0</string>
<key>NSHighResolutionCapable</key><true/> <key>NSHighResolutionCapable</key><true/>
<key>NSMicrophoneUsageDescription</key><string>語音聊天時,聽你說話。</string> <key>NSMicrophoneUsageDescription</key><string>語音聊天時,聽你說話。</string>

View File

@ -1826,7 +1826,7 @@ function drawSettings(kind, quiet) {
h += group("這支手機", acts.join("")); h += group("這支手機", acts.join(""));
} }
if (kind === "updates") { if (kind === "updates") {
h += group("", item({icon: "info", k: "版本", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"}))); h += group("", item({icon: "info", k: "版本", v: st.built ? `${st.built} 建置` : "", r: st.version || ""}) + (st.newer ? item({icon: "download", k: "有新版", v: "電腦上的 AnyBot 已經下載新版,重新啟動就會換上"}) : item({icon: "circle-check", k: "已是最新版"})));
h += `<div class="note">Bot 的電腦的更新在「電腦」裡。</div>`; h += `<div class="note">Bot 的電腦的更新在「電腦」裡。</div>`;
} }
el.innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`; el.innerHTML = h + `<div style="height:calc(var(--safe-b) + 24px)"></div>`;

View File

@ -325,7 +325,7 @@ impl App {
want_direct: Default::default(), want_direct: Default::default(),
managed: if demo { policy::Managed::default() } else { policy::read() }, managed: if demo { policy::Managed::default() } else { policy::read() },
settings_was_open: false, settings_was_open: false,
exe_built: exe_modified(), exe_built: crate::version::exe_modified(),
newer_build: None, newer_build: None,
last_build_check: Instant::now(), last_build_check: Instant::now(),
next_update_apply: Instant::now() + std::time::Duration::from_secs(notify::UPDATE_FIRST_CHECK_SECS), next_update_apply: Instant::now() + std::time::Duration::from_secs(notify::UPDATE_FIRST_CHECK_SECS),
@ -3567,9 +3567,9 @@ impl App {
} }
SettingsTab::Updates => { SettingsTab::Updates => {
section(ui, "AnyBot 更新", p); section(ui, "AnyBot 更新", p);
setting_row(ui, p, "版本", &version_label(self.exe_built), |ui| { setting_row(ui, p, "版本", &crate::version::full(self.exe_built), |ui| {
if let Some(tm) = self.newer_build { if let Some(tm) = self.newer_build {
ui.label(RichText::new(format!("{}{}", t("有更新的版本:"), version_label(Some(tm)))).size(12.0).color(p.accent)); ui.label(RichText::new(format!("{}{}", t("有更新的版本:"), crate::version::time_label(Some(tm)))).size(12.0).color(p.accent));
} else { } else {
ui.label(RichText::new(t("已是最新版本")).size(12.0).color(p.text3)); ui.label(RichText::new(t("已是最新版本")).size(12.0).color(p.text3));
} }
@ -3766,7 +3766,7 @@ impl App {
// Noticing a new build is a cheap file check, so the banner keeps up quickly (estimated 10 s). // Noticing a new build is a cheap file check, so the banner keeps up quickly (estimated 10 s).
if self.last_build_check.elapsed().as_secs() >= 10 { if self.last_build_check.elapsed().as_secs() >= 10 {
self.last_build_check = Instant::now(); self.last_build_check = Instant::now();
self.newer_build = match (exe_modified(), self.exe_built) { self.newer_build = match (crate::version::exe_modified(), self.exe_built) {
(Some(now), Some(started)) if now > started => Some(now), (Some(now), Some(started)) if now > started => Some(now),
_ => None, _ => None,
}; };
@ -4315,16 +4315,6 @@ impl eframe::App for App {
// ---------- helpers ---------- // ---------- helpers ----------
/// When the program file was last written (= when this build was made).
fn exe_modified() -> Option<std::time::SystemTime> {
std::env::current_exe().ok().and_then(|p| std::fs::metadata(p).ok()).and_then(|m| m.modified().ok())
}
/// "2026-11-03 20:57" in local time, or "?" when unknown.
fn version_label(t: Option<std::time::SystemTime>) -> String {
t.map(|t| chrono::DateTime::<chrono::Local>::from(t).format("%Y-%m-%d %H:%M").to_string()).unwrap_or_else(|| "?".into())
}
/// How often the relaunch helper checks whether the old copy has exited /// How often the relaunch helper checks whether the old copy has exited
/// (`while kill -0 "$pid" …; do sleep 0.2; done; exec "$app"`). /// (`while kill -0 "$pid" …; do sleep 0.2; done; exec "$app"`).
pub const RELAUNCH_POLL_SECS: f32 = 0.2; pub const RELAUNCH_POLL_SECS: f32 = 0.2;

View File

@ -1374,7 +1374,7 @@ impl App {
let log = crate::cloudbox::log_lines(); let log = crate::cloudbox::log_lines();
let mut out = json!({ let mut out = json!({
"role": if owner { "owner" } else { "admin" }, "role": if owner { "owner" } else { "admin" },
"host": st.remote.host_name, "version": version_label(self.exe_built), "newer": self.newer_build.is_some(), "host": st.remote.host_name, "version": crate::version::LABEL, "built": crate::version::time_label(self.exe_built), "newer": self.newer_build.is_some(),
"theme": match st.theme { Theme::Light => "light", Theme::Dark => "dark", Theme::System => "system" }, "theme": match st.theme { Theme::Light => "light", Theme::Dark => "dark", Theme::System => "system" },
"accent": serde_json::to_value(st.accent).unwrap_or_default(), "accent": serde_json::to_value(st.accent).unwrap_or_default(),
"timezone": st.timezone, "notify": st.notify, "language": st.language, "timezone": st.timezone, "notify": st.notify, "language": st.language,

View File

@ -203,7 +203,7 @@ impl App {
} }
}); });
if let Some(tm) = self.newer_build { if let Some(tm) = self.newer_build {
if crate::icons::pill(ui, crate::icons::Icon::Update, &format!("{}({})", t("重新啟動以更新"), version_label(Some(tm))), p.accent, Color32::WHITE, 30.0).clicked() { if crate::icons::pill(ui, crate::icons::Icon::Update, &format!("{}({})", t("重新啟動以更新"), crate::version::time_label(Some(tm))), p.accent, Color32::WHITE, 30.0).clicked() {
self.relaunch_requested = true; self.relaunch_requested = true;
} }
} }

View File

@ -63,6 +63,7 @@ mod docindex;
mod drops; mod drops;
mod vault; mod vault;
mod vault_store; mod vault_store;
mod version;
mod vnc; mod vnc;
mod voice; mod voice;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@ -248,6 +249,7 @@ const USAGE: &str = "用法:
anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用) anybot --ask 問題… 問第一個 Bot 一句,印出回答(測試用)
anybot setup … 在沒有螢幕的機器上設定 anybot setup … 在沒有螢幕的機器上設定
anybot --screenshot 檔名 把視窗畫成一張圖 anybot --screenshot 檔名 把視窗畫成一張圖
anybot --version 印出版本(v0.0.1-36bc2be · 建置時間)
資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)"; 資料夾:ANYBOT_DATA_DIR(沒設就用這個使用者的 AnyBot 資料夾)";
fn fetch_skill_text(src: &str) -> Result<String, String> { fn fetch_skill_text(src: &str) -> Result<String, String> {
@ -265,6 +267,11 @@ fn fetch_skill_text(src: &str) -> Result<String, String> {
fn main() -> eframe::Result<()> { fn main() -> eframe::Result<()> {
let args: Vec<String> = std::env::args().collect(); let args: Vec<String> = std::env::args().collect();
// Before anything else: no data folder, no window.
if matches!(args.get(1).map(String::as_str), Some("--version" | "-V")) {
println!("AnyBot {}", version::full(version::exe_modified()));
return Ok(());
}
// P7: install a skill file (a path or a URL) and be done: skills are .md files you can keep in a repo. // P7: install a skill file (a path or a URL) and be done: skills are .md files you can keep in a repo.
if let Some(i) = args.iter().position(|a| a == "--install-skill") { if let Some(i) = args.iter().position(|a| a == "--install-skill") {
let src = args.get(i + 1).cloned().unwrap_or_default(); let src = args.get(i + 1).cloned().unwrap_or_default();
@ -345,6 +352,8 @@ fn main() -> eframe::Result<()> {
} }
// No window: keep the bots working and answer the phone (always-on Mac or server). // No window: keep the bots working and answer the phone (always-on Mac or server).
if args.iter().any(|a| a == "--serve") { if args.iter().any(|a| a == "--serve") {
// The first line of the log says which build is running (make server-logs, journalctl).
eprintln!("AnyBot {}", version::full(version::exe_modified()));
let ctx = egui::Context::default(); let ctx = egui::Context::default();
let _folder = take_folder_or_exit(); let _folder = take_folder_or_exit();
app::App::serve(&ctx); app::App::serve(&ctx);

46
src/version.rs Normal file
View File

@ -0,0 +1,46 @@
//! Which build this is: "v0.0.1-36bc2be" (build.rs), and when it was built.
use std::time::SystemTime;
/// "v0.0.1-36bc2be", "v0.0.1-36bc2be-dirty" (built with uncommitted changes), or "v0.0.1".
pub const LABEL: &str = env!("ANYBOT_VERSION");
/// When the program file was last written (= when this build was made; a newer one replacing it is
/// how an update is noticed).
pub fn exe_modified() -> Option<SystemTime> {
std::env::current_exe().ok().and_then(|p| std::fs::metadata(p).ok()).and_then(|m| m.modified().ok())
}
/// "2026-11-03 20:57" in local time, or "?" when unknown.
pub fn time_label(t: Option<SystemTime>) -> String {
t.map(|t| chrono::DateTime::<chrono::Local>::from(t).format("%Y-%m-%d %H:%M").to_string()).unwrap_or_else(|| "?".into())
}
/// "v0.0.1-36bc2be · 2026-11-11 14:20": the version and when this build was made.
pub fn full(built: Option<SystemTime>) -> String {
match built {
Some(_) => format!("{LABEL} · {}", time_label(built)),
None => LABEL.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn label_is_v_number_dash_commit() {
let number = env!("CARGO_PKG_VERSION");
assert!(LABEL.starts_with(&format!("v{number}")), "{LABEL}");
let rest = &LABEL[1 + number.len()..];
// A commit, maybe "-dirty"; or nothing outside git.
assert!(rest.is_empty() || rest.starts_with('-'), "{LABEL}");
}
#[test]
fn full_adds_the_build_time() {
assert_eq!(full(None), LABEL);
let s = full(Some(SystemTime::UNIX_EPOCH));
assert!(s.starts_with(&format!("{LABEL} · ")) && s.len() > LABEL.len() + 10, "{s}");
}
}