` + SL.hits.map((k, i) => ``).join("");
el.querySelectorAll("[data-sl]").forEach((x) => {
// Keep the caret (and the phone's keyboard) in the input while a row is pressed.
x.onpointerdown = x.onmousedown = (e) => e.preventDefault();
@@ -1338,9 +1365,10 @@ async function send() {
const memories = b.busy ? undefined : memPicks();
memReset();
input.value = ""; input.style.height = "auto"; $("composer").classList.remove("tall"); S.pending = []; renderChips(); renderSlash();
- if (!b.busy) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
+ const quiet = /^\/goal(\s+(clear|stop|off|reset|none|cancel|清除|取消|停止))?\s*$/i.test(text);
+ if (!b.busy && !quiet) { S.msgs.push({role: "user", text, attachments: [], memories: memories || []}); renderMsgs(); $("scroller").scrollTop = 1e9; }
const body = {text, attachments}; if (memories) body.memories = memories;
- try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (b.busy) toast("已排入,Bot 會在下一步看到"); } catch (e) { toast(e.message); input.value = text; }
+ try { await api(base() + `api/bots/${S.open}/send`, {json: body}); if (quiet) loadChat(); else if (b.busy) toast("已排入,Bot 會在下一步看到"); } catch (e) { toast(e.message); input.value = text; }
}
$("b-plus").onclick = () => sheet("", [
{icon: "image", label: "照片與檔案", on: () => $("file").click()},
diff --git a/src/app.rs b/src/app.rs
index 483708f..202e076 100644
--- a/src/app.rs
+++ b/src/app.rs
@@ -39,6 +39,7 @@ mod pages_ui;
mod voice_ui;
mod drops_ui;
mod memory_ui;
+mod goal_ui;
// Sidebar rules from index.eager-app: defaults `FT={expandedWidth:280}` (),
// clamp `jT(..,240,400)` (), and the drag rule in `QJe` ():
@@ -229,6 +230,10 @@ pub struct App {
/// 群組聊天: members still to answer in this round, and groups whose next member should start.
group_queue: HashMap>,
group_next: Vec,
+ /// 目標: turns that ended since the last frame (checked in goal_tick), and the bots whose
+ /// goal is being checked now.
+ goal_due: Vec<(u64, TurnOutcome)>,
+ goal_checking: std::collections::HashSet,
/// 引用: the message being quoted in the next message, per bot.
quoting: HashMap,
/// Index of the message being drawn (for reactions).
@@ -318,6 +323,11 @@ impl App {
}
found.close()
};
+ // 目標: a goal that was going on has nothing running it after a restart; it says so and
+ // waits for the person (see goal::pause_all).
+ if !demo && screenshot.is_none() && crate::goal::pause_all(state.bots.iter_mut().filter_map(|b| b.goal.as_mut())) {
+ state.save();
+ }
crate::routines::set_person_timezone(&state.timezone);
let (tx, rx) = channel();
let mut app = App {
@@ -393,6 +403,8 @@ impl App {
share_rx: None,
group_queue: HashMap::new(),
group_next: vec![],
+ goal_due: vec![],
+ goal_checking: Default::default(),
quoting: HashMap::new(),
msg_index: 0,
rm: Default::default(),
@@ -452,6 +464,37 @@ impl App {
// Optional view for checking the dialogs in a picture.
match std::env::var("ANYBOT_SHOT_VIEW").as_deref() {
Ok("chat") => app.state.selected = 1,
+ // 目標: a goal on its way (ANYBOT_SHOT_GOAL=paused: stopped to ask), with the
+ // person's 「/goal …」, a 「還沒達成」 and a line of AnyBot's; ANYBOT_SHOT_DRAFT in the input.
+ Ok("goal") => {
+ app.state.selected = 1;
+ app.streams.clear();
+ app.approvals.clear();
+ let cond = "所有測試都通過,而且 cargo clippy 沒有新的警告";
+ let now = crate::model::now_ms();
+ if let Some(b) = app.state.bot_mut(1) {
+ b.messages.clear();
+ b.messages.push(Message { goal: cond.into(), at: now - 14 * 60_000, ..Message::user(&format!("/goal {cond}")) });
+ b.messages.push(Message { at: now - 12 * 60_000, ..Message::assistant("跑了 cargo test:338 個通過,2 個失敗(goal::tests 的時間格式)。先修這兩個。", "Anthropic · claude") });
+ b.messages.push(Message { wake: true, goal: cond.into(), at: now - 11 * 60_000, ..Message::user("[目標]還沒達成:cargo test 還有 2 個失敗,clippy 還沒跑") });
+ b.messages.push(Message { at: now - 6 * 60_000, ..Message::assistant("修好了時間格式,cargo test 全部 340 個通過;cargo clippy 沒有新的警告。", "Anthropic · claude") });
+ let mut g = crate::goal::Goal::new(cond, now - 14 * 60_000);
+ g.turns = 2;
+ g.reason = "cargo test 還有 2 個失敗,clippy 還沒跑".into();
+ if std::env::var("ANYBOT_SHOT_GOAL").as_deref() == Ok("paused") {
+ g.paused = "連續 3 輪沒有動手".into();
+ b.messages.push(Message { note: true, at: now - 60_000, ..Message::assistant("目標暫停:連續 3 輪都沒有實際動手,看起來卡住了。最近一次檢查:clippy 的輸出沒有出現在對話裡\n傳一句話就接著做;不要了就用 /goal clear。", "") });
+ }
+ if std::env::var("ANYBOT_SHOT_GOAL").as_deref() == Ok("met") {
+ b.messages.push(Message { note: true, at: now - 60_000, ..Message::assistant(&format!("目標達成:{cond}\ncargo test 340 個通過、clippy 沒有新警告,輸出都在對話裡(2 輪 · 14 分)"), "") });
+ } else {
+ b.goal = Some(g);
+ }
+ }
+ if let Ok(d) = std::env::var("ANYBOT_SHOT_DRAFT") {
+ app.drafts.insert(1, d);
+ }
+ }
// A chat long enough to scroll far up (回到底部; with ANYBOT_SHOT_SCROLL).
Ok("longchat") => {
app.state.selected = 1;
@@ -863,6 +906,12 @@ impl App {
self.drafts.insert(bot_id, String::new());
// Typed here: this computer is the person's.
self.typed_on = Some(String::new());
+ // 目標: 「/goal …」 is AnyBot's, not the bot's; anything else takes a paused goal up again.
+ if let Some(cmd) = crate::goal::command(&text) {
+ self.goal_command(ctx, bot_id, cmd, &text, attachments, picks);
+ return;
+ }
+ self.goal_heard(bot_id);
// While it works, a new message steers the running turn (the original's `turnSteer`:
// it doesn't count as a new turn) and reaches the model at its next step.
if self.streams.contains_key(&bot_id) {
@@ -1350,10 +1399,15 @@ impl App {
}
let away = self.away() && self.state.notify;
if let Some(l) = self.streams.remove(&bot_id) {
+ // 目標: whether it holds is checked next (goal_tick), and that check tells the person.
+ let on_the_way = self.state.bot(bot_id).and_then(|b| b.goal.as_ref()).is_some_and(|g| g.active());
+ if on_the_way {
+ self.goal_due.push((bot_id, outcome));
+ }
if let Some(b) = self.state.bot_mut(bot_id) {
b.last_turn = Some(TurnSettlement { turn_id: l.turn_id, outcome, settled_at_ms: chrono::Utc::now().timestamp_millis() });
// 「Bot 完成任務…時通知你」: a banner when it finishes while you're away.
- if outcome == TurnOutcome::Success && away && !self.demo {
+ if outcome == TurnOutcome::Success && away && !self.demo && !on_the_way {
let last = b.messages.iter().rev().find(|m| m.role == Role::Assistant && !m.text.is_empty()).map(|m| first_line(&m.text, 80)).unwrap_or_default();
if !self.headless {
notify::banner(&format!("{} 完成了", b.name), &last);
@@ -1702,6 +1756,11 @@ impl App {
self.dirty = true;
continue;
}
+ // 目標: the check after a turn has spoken.
+ if let StreamEvent::Goal(since, judged) = ev {
+ self.goal_verdict(ctx, id, since, judged);
+ continue;
+ }
// A stopped request may still deliver a few pieces; ignore them — also when the
// bot has a new turn running by now.
if self.streams.get(&id).map(|l| l.turn) != Some(turn) {
@@ -2047,6 +2106,7 @@ impl App {
context_tokens: agent::DEFAULT_CONTEXT_TOKENS,
routines: vec![],
last_turn: None,
+ goal: None,
default_computer: crate::model::default_computer(),
};
self.edit_bot = Some((b, true));
@@ -2788,6 +2848,8 @@ impl App {
self.attachments_poll(ctx, bot.id, had_focus);
self.voice_poll(ctx);
ui.add_space(4.0);
+ // 目標: how the goal stands, and 清除目標.
+ self.goal_bar(ui, ctx, bot);
// Quote and attachments sit just above the pill.
if let Some(q) = self.quoting.get(&bot.id).cloned() {
ui.horizontal(|ui| {
@@ -3975,6 +4037,7 @@ impl App {
return;
}
self.drain_events(ctx);
+ self.goal_tick(ctx);
if !self.demo {
self.channels_poll(ctx);
}
@@ -4093,12 +4156,14 @@ impl App {
app.send(ctx, id);
let t0 = Instant::now();
let limit = std::env::var("ANYBOT_ASK_SECS").ok().and_then(|v| v.parse().ok()).unwrap_or(900u64);
- while app.streams.contains_key(&id) && t0.elapsed().as_secs() < limit {
+ // 「/goal …」: on to the end, as Claude Code's `claude -p "/goal …"` does — turn, check, turn.
+ while (app.streams.contains_key(&id) || app.goal_pending(id)) && t0.elapsed().as_secs() < limit {
if let Some(a) = app.approvals.remove(&id) {
println!(" ⚠️ 要求核准(自動拒絕):{} — {}", a.tool, a.reason);
let _ = a.reply.send(ApprovalAnswer::Reject);
}
app.drain_events(ctx);
+ app.goal_tick(ctx);
app.watchdog();
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
std::thread::sleep(std::time::Duration::from_millis(100));
@@ -4496,15 +4561,19 @@ fn group_history(messages: &[Message], speaker: Option, st: &State) -> Vec<
let mut skip_tool_ids: std::collections::HashSet = Default::default();
// The model reads from the newest summary on (the chat itself keeps what was folded), and
// never the 「繼續」 cards a crash left (they are for the person).
- for m in messages[crate::model::model_view_start(messages)..].iter().filter(|m| !m.interrupted) {
+ for m in messages[crate::model::model_view_start(messages)..].iter().filter(|m| !m.interrupted && !m.note) {
let mut m = m.clone();
// After each of the person's messages: when it was sent and the memories it carried —
// made only from what the message keeps, so a chat reads the same every turn and the
// model's cache holds from the first message to the newest.
if m.role == Role::User && !m.summary {
m.context = crate::memory::context_of(&m, &st.timezone);
+ // 目標: what it works toward, and that a second model checks it.
+ if let Some(line) = crate::goal::context_line(&m) {
+ m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) };
+ }
// 「/pptx …」: the person picked the skill, so the model reads it before anything else.
- if let Some(k) = crate::memory::named_skill(&m.text, &st.skills) {
+ if let Some(k) = crate::memory::named_skill(&m.text, &st.skills).filter(|_| m.goal.is_empty()) {
let line = crate::memory::named_skill_line(k);
m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) };
}
diff --git a/src/app/chat_ui.rs b/src/app/chat_ui.rs
index c10aa9f..7dbbfb4 100644
--- a/src/app/chat_ui.rs
+++ b/src/app/chat_ui.rs
@@ -182,6 +182,8 @@ impl App {
});
ui.add_space(10.0);
}
+ // 目標: AnyBot's own line about the goal (set, met, paused…).
+ _ if m.note => self.goal_note_row(ui, m),
// Where AnyBot stopping cut a turn off: what it was doing and what may have run,
// with 「繼續」 while it is the newest thing in the chat.
_ if m.interrupted => {
@@ -598,7 +600,10 @@ impl App {
if self.slash.closed {
return vec![];
}
- let list: Vec<(String, String)> = crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().map(|k| (k.name.clone(), k.description.clone())).collect();
+ // AnyBot's own commands first (a skill by the same name can't be reached: the command
+ // takes the words), then the skills.
+ let mut list: Vec<(String, String)> = slash_commands(draft).into_iter().map(|(n, d)| (n.to_string(), t(d))).collect();
+ list.extend(crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().filter(|k| !SLASH_COMMANDS.iter().any(|(n, _)| *n == k.name)).map(|k| (k.name.clone(), k.description.clone())));
if draft != self.slash.draft {
self.slash.draft = draft.to_string();
self.slash.lit = 0;
@@ -639,7 +644,7 @@ impl App {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.add_space(10.0);
- ui.label(RichText::new(t("技能 · ↑↓ 選擇,Enter 帶入,Esc 關閉")).size(11.0).color(p.text3));
+ ui.label(RichText::new(t("指令和技能 · ↑↓ 選擇,Enter 帶入,Esc 關閉")).size(11.0).color(p.text3));
});
// Its full height even when the composer had less room last frame (the
// composer's room is last frame's height, so a squeezed list would stay squeezed).
@@ -696,11 +701,21 @@ fn jump_shows(from_bottom: f32, jumping: bool) -> bool {
from_bottom > JUMP_BOTTOM_AFTER && !jumping
}
+/// AnyBot's own / commands: (name, what it does). The brain acts on them itself (goal.rs).
+pub const SLASH_COMMANDS: [(&str, &str); 1] = [("goal", "設一個目標,一直做到達成為止(/goal clear 清除)")];
+
+/// The commands a draft like 「/go」 asks for (none once a space ends the name).
+pub fn slash_commands(draft: &str) -> Vec<(&'static str, &'static str)> {
+ let Some(q) = draft.strip_prefix('/').filter(|q| !q.chars().any(char::is_whitespace)) else { return vec![] };
+ let q = q.to_lowercase();
+ SLASH_COMMANDS.iter().copied().filter(|(n, _)| n.starts_with(&q)).collect()
+}
+
/// "[例行任務]…" → (icon, label) and the words after the tag.
pub fn wake_tag(text: &str) -> (Option<(crate::icons::Icon, &'static str)>, &str) {
use crate::icons::Icon;
// (The emoji forms are what older chats were saved with.)
- for (tag, icon, label) in [("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] {
+ for (tag, icon, label) in [("[目標]", Icon::Target, "目標"), ("[例行任務]", Icon::Alarm, "例行任務"), ("[觸發]", Icon::Zap, "觸發"), ("[訊息管道]", Icon::Message, "訊息管道"), ("[來自 Bot]", Icon::Bot, "來自其他 Bot"), ("⏰ ", Icon::Alarm, "例行任務"), ("⚡ ", Icon::Zap, "觸發"), ("💬 ", Icon::Message, "訊息管道"), ("📨 ", Icon::Bot, "來自其他 Bot")] {
if let Some(rest) = text.strip_prefix(tag) {
return (Some((icon, label)), rest);
}
@@ -728,6 +743,18 @@ mod tests {
assert!((pop(1.0) - 1.0).abs() < 1e-4 && pop(0.6) > 1.0);
}
+ #[test]
+ fn the_slash_list_offers_goal_first() {
+ assert_eq!(slash_commands("/").len(), SLASH_COMMANDS.len());
+ assert_eq!(slash_commands("/go").first().map(|c| c.0), Some("goal"));
+ assert_eq!(slash_commands("/GOAL").first().map(|c| c.0), Some("goal"));
+ assert!(slash_commands("/pptx").is_empty());
+ assert!(slash_commands("/goal 測試通過").is_empty(), "a space ends the name");
+ assert!(slash_commands("goal").is_empty());
+ let (tag, body) = wake_tag("[目標]還沒達成:還有 1 個失敗");
+ assert_eq!((tag.map(|t| t.1), body), (Some("目標"), "還沒達成:還有 1 個失敗"));
+ }
+
#[test]
fn jump_to_bottom_shows_far_up_and_lets_go() {
// Near the newest message: no button. Far up: the button.
diff --git a/src/app/goal_ui.rs b/src/app/goal_ui.rs
new file mode 100644
index 0000000..e80a58a
--- /dev/null
+++ b/src/app/goal_ui.rs
@@ -0,0 +1,259 @@
+// 目標 (/goal) in the window: 「/goal …」 typed to this brain (here, on one of its screens, on the
+// phone), the check after each turn, and the line above the input. What a goal is, how it is
+// judged and when it stops: goal.rs.
+//
+// The loop: a turn ends (settle) → its goal, if one is going, is checked by a second model on a
+// thread of its own (goal_tick → goal_judge) → the verdict comes back as StreamEvent::Goal
+// (goal_verdict) → not yet: AnyBot's 「[目標]還沒達成:…」 wakes the bot for another turn; met,
+// impossible or paused: a line in the chat (a note, never sent to the model) and, when the
+// person is away, a notification. Only a brain does this: a screen's turns run on its brain.
+
+use super::*;
+use crate::goal::{self, Command, Goal, Judged, Next};
+
+impl App {
+ /// 「/goal …」: show, clear, or set the goal and start on it.
+ pub(super) fn goal_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: Command, text: &str, attachments: Vec, picks: Option>) {
+ let now = crate::model::now_ms();
+ let Some(b) = self.state.bot(bot_id) else { return };
+ match cmd {
+ Command::Status => {
+ let s = goal::status(b.goal.as_ref(), now);
+ self.goal_note(bot_id, &s);
+ }
+ Command::Clear => {
+ let s = match self.state.bot_mut(bot_id).and_then(|b| b.goal.take()) {
+ Some(g) => format!("已清除目標:{}", g.condition),
+ None => "沒有設定目標。".into(),
+ };
+ self.goal_checking.remove(&bot_id);
+ self.goal_note(bot_id, &s);
+ }
+ Command::Set(cond) => {
+ if !b.members.is_empty() {
+ self.goal_note(bot_id, "群組聊天還不能設目標。");
+ return;
+ }
+ if cond.chars().count() > goal::MAX_CONDITION_CHARS {
+ self.goal_note(bot_id, &format!("目標太長了(最多 {} 字)。", goal::MAX_CONDITION_CHARS));
+ return;
+ }
+ self.goal_checking.remove(&bot_id);
+ if self.streams.contains_key(&bot_id) {
+ // Working: the running turn hears it at its next step, and its end is the
+ // first one checked.
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ b.goal = Some(Goal::new(&cond, now));
+ }
+ self.queue_steer(bot_id, text.trim().to_string());
+ } else {
+ let m = Message { goal: cond.clone(), ..person_message(&self.state, bot_id, text.trim(), attachments, picks) };
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ b.goal = Some(Goal::new(&cond, m.at));
+ b.messages.push(m);
+ }
+ self.start_reply(ctx, bot_id);
+ }
+ }
+ }
+ self.dirty = true;
+ self.save_now = true;
+ }
+
+ /// The person wrote to the bot (not 「/goal」): a paused goal goes on with this turn.
+ pub(super) fn goal_heard(&mut self, bot_id: u64) {
+ if let Some(g) = self.state.bot_mut(bot_id).and_then(|b| b.goal.as_mut()) {
+ g.resume();
+ }
+ }
+
+ /// 清除目標 above the input: on a screen the brain clears it, as if typed there.
+ pub(super) fn goal_clear(&mut self, ctx: &egui::Context, bot_id: u64) {
+ if self.mir.on {
+ self.mirror_send(bot_id, "/goal clear".into(), vec![], None);
+ return;
+ }
+ self.goal_command(ctx, bot_id, Command::Clear, "/goal clear", vec![], None);
+ }
+
+ /// AnyBot's own line in the chat. While the bot works, its newest message is the one the
+ /// words stream into, so the line goes just before it.
+ fn goal_note(&mut self, bot_id: u64, text: &str) {
+ let streaming = self.streams.contains_key(&bot_id);
+ let selected = self.state.selected;
+ if let Some(b) = self.state.bot_mut(bot_id) {
+ let m = Message { note: true, ..Message::assistant(text, "") };
+ match b.messages.len() {
+ n if streaming && n > 0 => b.messages.insert(n - 1, m),
+ _ => b.messages.push(m),
+ }
+ if bot_id != selected {
+ b.unread = true;
+ }
+ }
+ self.dirty = true;
+ }
+
+ /// Tell the person how the goal stands, the way a finished turn is told (only when away).
+ fn goal_tell(&self, bot_id: u64, title: &str, note: &str) {
+ if self.demo || !(self.away() && self.state.notify) {
+ return;
+ }
+ let body = first_line(¬e.replace('\n', " "), 120);
+ if !self.headless {
+ notify::banner(title, &body);
+ }
+ crate::remote::notify(title, &body, bot_id);
+ }
+
+ /// A turn of this bot's goal has ended and its check hasn't spoken yet.
+ pub(super) fn goal_pending(&self, bot_id: u64) -> bool {
+ self.goal_checking.contains(&bot_id) || self.goal_due.iter().any(|(id, _)| *id == bot_id)
+ }
+
+ /// Turns that ended since the last frame: check the ones working toward a goal.
+ pub(super) fn goal_tick(&mut self, ctx: &egui::Context) {
+ for (bot_id, outcome) in std::mem::take(&mut self.goal_due) {
+ // Another turn is on its way (typed meanwhile, the next group member): its end is
+ // the one checked.
+ if self.streams.contains_key(&bot_id) || self.pending_turns.iter().any(|(id, _)| *id == bot_id) || self.group_next.contains(&bot_id) {
+ continue;
+ }
+ let Some(b) = self.state.bot_mut(bot_id) else { continue };
+ let Some(g) = b.goal.as_mut().filter(|g| g.active()) else { continue };
+ match outcome {
+ TurnOutcome::Success => {
+ let start = b.messages.iter().rposition(|m| m.role == Role::User && !m.steer).unwrap_or(0);
+ g.after_turn(b.messages[start..].iter().any(|m| m.role == Role::Assistant && !m.tool_calls.is_empty()));
+ let g = g.clone();
+ self.goal_judge(ctx, bot_id, g);
+ }
+ TurnOutcome::Cancelled | TurnOutcome::Error => {
+ let note = goal::after_trouble(g, outcome == TurnOutcome::Cancelled);
+ let title = format!("{} 的目標暫停了", b.name);
+ self.goal_note(bot_id, ¬e);
+ self.goal_tell(bot_id, &title, ¬e);
+ }
+ }
+ self.dirty = true;
+ }
+ }
+
+ /// Ask the bot's quick model (or its own, as its 執行步驟用的模型 setting says) whether the
+ /// goal holds, on a thread; the answer comes back as StreamEvent::Goal.
+ fn goal_judge(&mut self, ctx: &egui::Context, bot_id: u64, g: Goal) {
+ let Some(b) = self.state.bot(bot_id) else { return };
+ let ps = self.state.provider(b.provider);
+ let model = match b.step_model.trim() {
+ "off" => b.model.clone(),
+ "" => b.provider.quick_model(&b.model).map(String::from).unwrap_or_else(|| b.model.clone()),
+ m => m.to_string(),
+ };
+ let req = ChatRequest {
+ kind: b.provider,
+ base_url: providers::resolve_base(b.provider, &ps.base_url),
+ api_key: providers::resolve_key(b.provider, &ps.api_key),
+ model,
+ system: goal::JUDGE_SYSTEM.into(),
+ history: vec![Message::user(&goal::brief(&g, &b.messages, crate::model::now_ms()))],
+ tools: vec![],
+ session: format!("anybot-goal-{bot_id}"),
+ };
+ self.goal_checking.insert(bot_id);
+ let (tx, ctx) = (self.tx.clone(), ctx.clone());
+ std::thread::spawn(move || {
+ let cancel = AtomicBool::new(false);
+ let judged = match providers::run_step(&req, &cancel, &|_| {}) {
+ Ok(o) => goal::read_verdict(&o.text),
+ Err(e) => Judged::Failed(e),
+ };
+ eprintln!("AnyBot:Bot {bot_id} 的目標檢查:{judged:?}");
+ let _ = tx.send((bot_id, 0, StreamEvent::Goal(g.since, judged)));
+ ctx.request_repaint();
+ });
+ }
+
+ /// The check has spoken: another turn, or a line saying it is over or paused.
+ pub(super) fn goal_verdict(&mut self, ctx: &egui::Context, bot_id: u64, since: i64, judged: Judged) {
+ self.goal_checking.remove(&bot_id);
+ // The person already started another turn: its end is checked instead.
+ if self.streams.contains_key(&bot_id) {
+ return;
+ }
+ let Some(b) = self.state.bot_mut(bot_id) else { return };
+ let name = b.name.clone();
+ // Cleared, or set again, while it was being checked.
+ let Some(g) = b.goal.as_mut().filter(|g| g.since == since && g.active()) else { return };
+ let next = goal::after_verdict(g, judged, crate::model::now_ms());
+ let condition = g.condition.clone();
+ match next {
+ Next::Over { note, title } => {
+ b.goal = None;
+ self.goal_note(bot_id, ¬e);
+ self.goal_tell(bot_id, &format!("{name} {title}"), ¬e);
+ }
+ Next::Pause { note, title } => {
+ self.goal_note(bot_id, ¬e);
+ self.goal_tell(bot_id, &format!("{name} {title}"), ¬e);
+ }
+ Next::Again { text } => self.wake(ctx, bot_id, Message { wake: true, goal: condition, ..Message::user(&text) }),
+ }
+ self.dirty = true;
+ self.save_now = true;
+ }
+
+ /// The line above the input while there is a goal: how it stands (the goal and the newest
+ /// check on hover) and 清除目標. The words end in … before the button on a narrow window.
+ pub(super) fn goal_bar(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) {
+ let Some(g) = bot.goal.as_ref() else { return };
+ let p = self.pal;
+ let now = crate::model::now_ms();
+ let text = if g.active() && self.goal_checking.contains(&bot.id) { t("目標 · 正在檢查有沒有達成…") } else { goal::bar_text(g, now) };
+ let mut tip = format!("{}{}", t("目標:"), g.condition);
+ if !g.reason.is_empty() {
+ tip.push_str(&format!("\n\n{}{}", t("最近一次檢查:"), g.reason));
+ }
+ let col = if g.active() { p.text2 } else { p.text3 };
+ let mut clear = false;
+ ui.horizontal(|ui| {
+ ui.add_space(14.0);
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.add_space(10.0);
+ clear = small_button(ui, "清除目標", p).clicked();
+ ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
+ ui.spacing_mut().item_spacing.x = 6.0;
+ let (r, _) = ui.allocate_exact_size(vec2(13.0, 14.0), egui::Sense::hover());
+ crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, if g.active() { p.accent } else { col });
+ ui.add(egui::Label::new(RichText::new(&text).size(FONT_XS).color(col)).truncate().selectable(false)).on_hover_text(&tip);
+ });
+ });
+ });
+ ui.add_space(2.0);
+ if clear {
+ self.goal_clear(ctx, bot.id);
+ }
+ if g.active() {
+ // The minutes count on.
+ ctx.request_repaint_after(std::time::Duration::from_secs(30));
+ }
+ }
+
+ /// A goal's line in the chat (AnyBot's, not the bot's): small, in the middle.
+ pub(super) fn goal_note_row(&self, ui: &mut egui::Ui, m: &Message) {
+ let p = self.pal;
+ ui.add_space(2.0);
+ ui.vertical_centered(|ui| {
+ let w = message_max_width(ui.available_width());
+ ui.set_max_width(w);
+ Frame::new().fill(p.hover).corner_radius(12).inner_margin(Margin::symmetric(12, 7)).show(ui, |ui| {
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing.x = 6.0;
+ let (r, _) = ui.allocate_exact_size(vec2(13.0, 16.0), egui::Sense::hover());
+ crate::icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), crate::icons::Icon::Target, p.text3);
+ ui.add(egui::Label::new(RichText::new(&m.text).size(12.5).line_height(Some(18.0)).color(p.text2)).wrap());
+ });
+ });
+ });
+ ui.add_space(10.0);
+ }
+}
diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs
index 177c826..e3ea6de 100644
--- a/src/app/mirror_ui.rs
+++ b/src/app/mirror_ui.rs
@@ -18,7 +18,7 @@ use std::sync::atomic::AtomicU64;
/// Settings that belong to each computer, never to the brain.
const LOCAL_KEYS: &[&str] = &["remote", "theme", "accent", "sidebar_collapsed", "sidebar_width", "selected", "machine_label", "local_execution", "local_never", "messages_send", "messages_no_ask"];
/// Bot fields the brain alone changes (its chat, and what a turn leaves behind).
-const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "context_tokens"];
+const BOT_RUNTIME: &[&str] = &["id", "messages", "threads", "unread", "last_turn", "context_tokens", "goal"];
/// Stands in for a key or token the brain doesn't hand out.
pub const REDACTED: &str = "••••(已設定,在大腦上)";
diff --git a/src/app/remote_ui.rs b/src/app/remote_ui.rs
index 21fa5f7..4d262fd 100644
--- a/src/app/remote_ui.rs
+++ b/src/app/remote_ui.rs
@@ -316,6 +316,11 @@ impl App {
// The sidebar's sections, the colour by name (the editor), what is queued while it works.
"folder": b.folder, "color_key": b.color,
"queued": live.map(|l| l.steer.lock().unwrap().iter().map(|q| q.text.clone()).collect::>()).unwrap_or_default(),
+ // 目標: how it stands (the line above the input), worded here so the phone says it the same way.
+ "goal": b.goal.as_ref().map(|g| json!({
+ "condition": g.condition, "reason": g.reason, "active": g.active(),
+ "line": if g.active() && self.goal_checking.contains(&b.id) { "目標 · 正在檢查有沒有達成…".to_string() } else { crate::goal::bar_text(g, crate::model::now_ms()) },
+ })),
}));
let start = b.messages.len().saturating_sub(remote::PHONE_TAIL);
// Each message with its place in the chat (表情回應), its thinking and, on each step,
@@ -407,6 +412,12 @@ impl App {
Some(crate::attach::Attachment { image: crate::attach::is_image_name(&name), name, path: f.display().to_string(), bytes: meta.len(), on_box })
})
.collect();
+ // 目標: 「/goal …」 is AnyBot's, not the bot's; anything else takes a paused goal up again.
+ if let Some(cmd) = crate::goal::command(&text) {
+ self.goal_command(ctx, bot, cmd, &text, atts, memories);
+ return;
+ }
+ self.goal_heard(bot);
if self.streams.contains_key(&bot) {
let (extra, _) = crate::attach::for_model(&atts);
self.queue_steer(bot, format!("{text}{extra}"));
diff --git a/src/appctl.rs b/src/appctl.rs
index 352bab8..cee3892 100644
--- a/src/appctl.rs
+++ b/src/appctl.rs
@@ -562,6 +562,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
context_tokens: model::default_context_tokens(),
routines: vec![],
last_turn: None,
+ goal: None,
default_computer: model::default_computer(),
});
ok(format!("已建立 Bot「{name}」({} · {model})", provider.label()))
diff --git a/src/goal.rs b/src/goal.rs
new file mode 100644
index 0000000..2c5ee20
--- /dev/null
+++ b/src/goal.rs
@@ -0,0 +1,450 @@
+//! 目標 (/goal): a condition a bot keeps working toward, turn after turn, until a second model —
+//! one that didn't do the work — reads the chat and says it holds. Claude Code's /goal
+//! (code.claude.com/docs/en/goal): after every turn a small fast model judges the condition met,
+//! not yet met (its reason guides the next turn, which starts by itself) or impossible.
+//!
+//! The goal lives on the brain, on the bot (`Bot::goal`); screens and the phone show it. The person
+//! sets it with 「/goal 條件」, sees it with 「/goal」 and clears it with 「/goal clear」. Nothing
+//! here draws or runs anything: the command, the judge's brief and how its answer is read, and
+//! the brakes. The window runs it after each turn (app/goal_ui.rs).
+//!
+//! The brakes are tighter than Claude Code's: one AnyBot turn can be 100 steps on the person's own
+//! keys, so a goal stops to ask after [`TURNS`] turns, after [`IDLE_TURNS`] turns that did nothing,
+//! and whenever the bot is waiting for the person (a question asked in words ends the turn; going
+//! on without the answer would only ask again).
+
+use serde::{Deserialize, Serialize};
+
+use crate::model::{Message, Role};
+
+/// Longest condition (Claude Code: 4,000 characters).
+pub const MAX_CONDITION_CHARS: usize = 4_000;
+/// Turns a goal runs before it stops to ask; the person's next message gives it as many again
+/// (estimated).
+pub const TURNS: u32 = 20;
+/// Turns in a row that used no tool before it stops: the bot is only talking to the judge.
+/// (Claude Code stops after "several turns in a row" without tool use; estimated.)
+pub const IDLE_TURNS: u32 = 3;
+/// How much of the chat the judge reads, the newest kept (estimated).
+const BRIEF_CHARS: usize = 24_000;
+/// Each piece of the chat in the judge's brief, at most (estimated).
+const TEXT_CHARS: usize = 2_500;
+const ARGS_CHARS: usize = 300;
+/// A tool's result: its start and its end (where a test run says how it went).
+const RESULT_HEAD: usize = 400;
+const RESULT_TAIL: usize = 1_100;
+/// The tag on AnyBot's 「還沒達成」 that starts the next turn (see app::chat_ui::wake_tag).
+pub const TAG: &str = "[目標]";
+
+/// A bot's goal, kept on the bot (it survives restarts; see `pause_all`).
+#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Default)]
+pub struct Goal {
+ pub condition: String,
+ /// When it was set (ms): the time of the person's 「/goal …」 message, where the judge's
+ /// reading starts.
+ pub since: i64,
+ /// Turns judged so far.
+ #[serde(default)]
+ pub turns: u32,
+ /// It stops to ask when `turns` reaches this.
+ #[serde(default)]
+ pub until: u32,
+ /// Turns in a row that used no tool.
+ #[serde(default)]
+ pub idle: u32,
+ /// The judge's newest reason.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub reason: String,
+ /// Not going on by itself, and why. The person's next message takes it up again.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub paused: String,
+}
+
+impl Goal {
+ pub fn new(condition: &str, since: i64) -> Goal {
+ Goal { condition: condition.trim().to_string(), since, until: TURNS, ..Default::default() }
+ }
+
+ pub fn active(&self) -> bool {
+ self.paused.is_empty()
+ }
+
+ /// A turn ended: did it do anything (use a tool)?
+ pub fn after_turn(&mut self, used_tools: bool) {
+ self.idle = if used_tools { 0 } else { self.idle + 1 };
+ }
+
+ /// The person wrote: a paused goal goes on, with as many turns again if it had used them up.
+ pub fn resume(&mut self) {
+ self.paused.clear();
+ self.idle = 0;
+ if self.turns >= self.until {
+ self.until = self.turns + TURNS;
+ }
+ }
+}
+
+/// What 「/goal …」 asks for.
+#[derive(Debug, PartialEq)]
+pub enum Command {
+ /// 「/goal」: how it stands.
+ Status,
+ /// 「/goal clear」 (stop, off, reset, none, cancel, 清除, 取消, 停止).
+ Clear,
+ /// 「/goal 條件」: set (or replace) the goal and start on it.
+ Set(String),
+}
+
+/// 「/goal」, 「/goal clear」 or 「/goal 條件」; None for anything else (「/goals」 too).
+pub fn command(text: &str) -> Option {
+ let rest = text.trim().strip_prefix("/goal")?;
+ if rest.chars().next().is_some_and(|c| !c.is_whitespace()) {
+ return None;
+ }
+ let arg = rest.trim();
+ Some(match arg.to_lowercase().as_str() {
+ "" => Command::Status,
+ "clear" | "stop" | "off" | "reset" | "none" | "cancel" | "清除" | "取消" | "停止" => Command::Clear,
+ _ => Command::Set(arg.to_string()),
+ })
+}
+
+/// What the judge said.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Verdict {
+ Met,
+ NotYet,
+ /// The bot is waiting for the person (a question, a sign-in, a decision).
+ Waiting,
+ Impossible,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum Judged {
+ Said(Verdict, String),
+ /// The judge's model didn't answer.
+ Failed(String),
+}
+
+/// The judge's instructions.
+pub const JUDGE_SYSTEM: &str = "你是驗收員。使用者給一個 bot 設了目標,bot 剛做完一輪。你只能看下面的對話紀錄(bot 說的話、它用了哪些工具、工具回了什麼),判斷目標現在是不是已經成立。
+
+- 只認對話裡看得到的證據:指令的輸出、測試結果、檔案內容、畫面、網頁內容。bot 自己說「做完了」「應該可以了」不算證據。
+- 目標裡有輪數或時間的限制(例如「最多 10 輪」),照紀錄開頭寫的輪數和時間判斷。
+- bot 在問使用者問題、等使用者決定,或要使用者做只有他能做的事(登入、付款、給密碼)才能繼續:判 waiting。
+- 確定永遠做不到才判 impossible(要的東西不存在、被明確拒絕而且沒有別的路);只是還沒做完、遇到能修的錯誤,都是 not_met。
+- reason 一句話,用使用者的語言:met 寫是哪個證據;not_met 寫還差什麼、下一步做什麼;waiting 寫在等使用者什麼;impossible 寫為什麼。
+
+只回一個 JSON,不要別的字:{\"verdict\":\"met|not_met|waiting|impossible\",\"reason\":\"…\"}";
+
+/// The judge's answer, read loosely (a model may wrap the JSON in words or a code fence). An
+/// answer that can't be read counts as not yet met: the turn cap still stops it.
+pub fn read_verdict(text: &str) -> Judged {
+ let json = text.find('{').zip(text.rfind('}')).filter(|(a, b)| a < b).and_then(|(a, b)| serde_json::from_str::(&text[a..=b]).ok());
+ let Some(v) = json else {
+ let said = clip(&one_line(text), 200);
+ return Judged::Said(Verdict::NotYet, if said.is_empty() { "(檢查的模型沒有給出結果)".into() } else { said });
+ };
+ let verdict = match v["verdict"].as_str().unwrap_or("").trim().to_lowercase().replace([' ', '-'], "_").as_str() {
+ "met" | "achieved" | "done" | "yes" => Verdict::Met,
+ "waiting" | "wait" | "ask" | "needs_user" | "need_user" => Verdict::Waiting,
+ "impossible" | "failed" | "cannot" => Verdict::Impossible,
+ _ => Verdict::NotYet,
+ };
+ Judged::Said(verdict, clip(&one_line(v["reason"].as_str().unwrap_or("")), 300))
+}
+
+/// What the judge reads: the goal, how long and how many turns, and the chat since it was set
+/// (the newest part when it is long).
+pub fn brief(g: &Goal, msgs: &[Message], now: i64) -> String {
+ let start = msgs.iter().position(|m| m.at >= g.since).unwrap_or(0);
+ let mut parts: Vec = vec![];
+ for m in &msgs[start..] {
+ if m.note || m.interrupted {
+ continue;
+ }
+ match m.role {
+ _ if m.summary => parts.push(format!("【較早的對話摘要】{}", clip(&m.text, TEXT_CHARS))),
+ Role::User if m.wake && m.text.starts_with(TAG) => parts.push(format!("【上一次檢查】{}", clip(m.text.trim_start_matches(TAG), TEXT_CHARS))),
+ Role::User => parts.push(format!("【使用者】{}", clip(&m.text, TEXT_CHARS))),
+ Role::Assistant => {
+ if !m.text.trim().is_empty() {
+ parts.push(format!("【bot】{}", clip(&m.text, TEXT_CHARS)));
+ }
+ for c in &m.tool_calls {
+ parts.push(format!("【bot 用了 {}】{}", c.name, clip(&one_line(&c.args), ARGS_CHARS)));
+ }
+ }
+ Role::Tool => parts.push(format!("【{} 的結果】{}", m.tool_name, head_tail(&m.text, RESULT_HEAD, RESULT_TAIL))),
+ }
+ }
+ let mut chat = parts.join("\n\n");
+ let n = chat.chars().count();
+ if n > BRIEF_CHARS {
+ chat = format!("(前面較早的部分省略)\n…{}", chat.chars().skip(n - BRIEF_CHARS).collect::());
+ }
+ format!(
+ "目標:{}\n\n目標設定了 {},現在是第 {} 輪剛結束。\n\n對話紀錄:\n\n{chat}\n\n目標現在成立了嗎?只回 JSON。",
+ g.condition,
+ elapsed(now - g.since),
+ g.turns + 1
+ )
+}
+
+/// What happens after the judge has spoken.
+#[derive(Debug, PartialEq)]
+pub enum Next {
+ /// The goal is over (met, or never can be): clear it and say so.
+ Over { note: String, title: &'static str },
+ /// It stops going on by itself and says why (kept: the person's next message goes on).
+ Pause { note: String, title: &'static str },
+ /// Another turn, started by this message (AnyBot's, tagged 「[目標]」).
+ Again { text: String },
+}
+
+/// Count the turn and decide what comes next. The goal is changed in place (turns, reason,
+/// paused); `Over` means the caller clears it.
+pub fn after_verdict(g: &mut Goal, judged: Judged, now: i64) -> Next {
+ let (verdict, reason) = match judged {
+ Judged::Said(v, r) => (v, r),
+ Judged::Failed(e) => {
+ g.paused = "檢查目標時模型沒有回應".into();
+ return Next::Pause { note: format!("目標暫停:檢查目標時模型沒有回應({})。傳一句話就接著做。", clip(&one_line(&e), 160)), title: "的目標暫停了" };
+ }
+ };
+ g.turns += 1;
+ g.reason = reason.clone();
+ let took = format!("{} 輪 · {}", g.turns, elapsed(now - g.since));
+ match verdict {
+ Verdict::Met => Next::Over { note: format!("目標達成:{}\n{reason}({took})", g.condition), title: "達成目標了" },
+ Verdict::Impossible => Next::Over { note: format!("目標做不到,已清除:{}\n{reason}({took})", g.condition), title: "的目標做不到" },
+ Verdict::Waiting => {
+ g.paused = "等你回覆".into();
+ Next::Pause { note: format!("目標暫停,等你回覆:{reason}"), title: "在等你回覆" }
+ }
+ Verdict::NotYet if g.turns >= g.until => {
+ g.paused = format!("已經做了 {} 輪", g.turns);
+ Next::Pause { note: format!("目標暫停:已經做了 {} 輪還沒達成。最近一次檢查:{reason}\n傳一句話(例如「繼續」)就再做 {TURNS} 輪;不要了就用 /goal clear。", g.turns), title: "的目標暫停了" }
+ }
+ Verdict::NotYet if g.idle >= IDLE_TURNS => {
+ g.paused = format!("連續 {IDLE_TURNS} 輪沒有動手");
+ Next::Pause { note: format!("目標暫停:連續 {IDLE_TURNS} 輪都沒有實際動手,看起來卡住了。最近一次檢查:{reason}\n傳一句話就接著做;不要了就用 /goal clear。"), title: "的目標暫停了" }
+ }
+ Verdict::NotYet => Next::Again { text: format!("{TAG}還沒達成:{reason}") },
+ }
+}
+
+/// A turn ended badly: the goal stops going on by itself (kept), and the chat says why.
+pub fn after_trouble(g: &mut Goal, stopped: bool) -> String {
+ if stopped {
+ g.paused = "你按了停止".into();
+ "目標暫停:你按了停止。傳一句話就接著做;不要了就用 /goal clear。".into()
+ } else {
+ g.paused = "這一輪出錯了".into();
+ "目標暫停:這一輪出錯了。傳一句話就接著做;不要了就用 /goal clear。".into()
+ }
+}
+
+/// AnyBot starting again: a goal that was going on has nothing running it any more (a turn cut
+/// off waits for its 「繼續」, a check that was under way is lost). Say so instead of looking busy.
+pub fn pause_all<'a>(goals: impl Iterator) -> bool {
+ let mut changed = false;
+ for g in goals.filter(|g| g.active()) {
+ g.paused = "AnyBot 重新啟動過".into();
+ changed = true;
+ }
+ changed
+}
+
+/// What the model reads after the person's 「/goal …」 or AnyBot's 「還沒達成」 (app::group_history).
+pub fn context_line(m: &Message) -> Option {
+ if m.goal.is_empty() {
+ return None;
+ }
+ Some(if m.wake {
+ format!("〔目標「{}」還沒達成,上面是檢查的理由。接著做,用實際的結果證明進度;需要使用者回答或動手才能繼續,就直接問他。〕", m.goal)
+ } else {
+ format!(
+ "〔使用者用 /goal 設了目標:「{}」。把它做到成立為止。每一輪結束後,會有另一個模型只看這段對話判斷目標達成了沒有,沒達成就會叫你接著做;所以要用實際的結果證明(指令的輸出、測試結果、檔案內容、畫面),不能只說做完了。需要使用者回答或動手才能繼續,就直接問他。真的做不到,就說清楚為什麼。〕",
+ m.goal
+ )
+ })
+}
+
+/// 「/goal」 with nothing after it.
+pub fn status(g: Option<&Goal>, now: i64) -> String {
+ let Some(g) = g else { return "沒有設定目標。用「/goal 條件」設一個,例如「/goal 所有測試都通過」。".into() };
+ let mut s = format!("目前的目標:{}\n已經 {} · 檢查了 {} 輪", g.condition, elapsed(now - g.since), g.turns);
+ if !g.reason.is_empty() {
+ s.push_str(&format!("\n最近一次檢查:{}", g.reason));
+ }
+ if !g.paused.is_empty() {
+ s.push_str(&format!("\n已暫停({}):傳一句話就接著做。", g.paused));
+ }
+ s
+}
+
+/// The one line above the input while there is a goal.
+pub fn bar_text(g: &Goal, now: i64) -> String {
+ if g.active() {
+ format!("目標進行中 · {} · {} 輪", elapsed(now - g.since), g.turns)
+ } else {
+ format!("目標暫停 · {}", g.paused)
+ }
+}
+
+/// 「40 秒」「12 分」「1 小時 5 分」.
+pub fn elapsed(ms: i64) -> String {
+ let s = (ms.max(0) / 1000) as u64;
+ match s {
+ 0..60 => format!("{s} 秒"),
+ 60..3600 => format!("{} 分", s / 60),
+ _ if s % 3600 < 60 => format!("{} 小時", s / 3600),
+ _ => format!("{} 小時 {} 分", s / 3600, s % 3600 / 60),
+ }
+}
+
+fn one_line(s: &str) -> String {
+ s.split_whitespace().collect::>().join(" ")
+}
+
+fn clip(s: &str, n: usize) -> String {
+ let s = s.trim();
+ if s.chars().count() <= n {
+ return s.to_string();
+ }
+ format!("{}…", s.chars().take(n).collect::())
+}
+
+fn head_tail(s: &str, head: usize, tail: usize) -> String {
+ let s = s.trim();
+ let n = s.chars().count();
+ if n <= head + tail {
+ return s.to_string();
+ }
+ format!("{}\n…(中間省略 {} 字)…\n{}", s.chars().take(head).collect::(), n - head - tail, s.chars().skip(n - tail).collect::())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::ToolCall;
+
+ #[test]
+ fn the_command_sets_shows_and_clears() {
+ assert_eq!(command("/goal"), Some(Command::Status));
+ assert_eq!(command(" /goal "), Some(Command::Status));
+ assert_eq!(command("/goal clear"), Some(Command::Clear));
+ assert_eq!(command("/goal STOP"), Some(Command::Clear));
+ assert_eq!(command("/goal 取消"), Some(Command::Clear));
+ assert_eq!(command("/goal 所有測試都通過"), Some(Command::Set("所有測試都通過".into())));
+ assert_eq!(command("/goal\n多行\n條件"), Some(Command::Set("多行\n條件".into())));
+ // Not the command: another word, or not at the start.
+ assert_eq!(command("/goals"), None);
+ assert_eq!(command("/goalkeeper 是誰"), None);
+ assert_eq!(command("我的 /goal 是"), None);
+ assert_eq!(command("/pptx 做簡報"), None);
+ }
+
+ #[test]
+ fn the_judges_answer_is_read_loosely() {
+ assert_eq!(read_verdict(r#"{"verdict":"met","reason":"npm test 結束碼 0"}"#), Judged::Said(Verdict::Met, "npm test 結束碼 0".into()));
+ assert_eq!(read_verdict("```json\n{\"verdict\": \"not_met\", \"reason\": \"還有 2 個測試失敗\"}\n```"), Judged::Said(Verdict::NotYet, "還有 2 個測試失敗".into()));
+ assert_eq!(read_verdict(r#"{"verdict":"waiting","reason":"等使用者登入"}"#), Judged::Said(Verdict::Waiting, "等使用者登入".into()));
+ assert_eq!(read_verdict(r#"{"verdict":"impossible","reason":"沒有這個檔案"}"#), Judged::Said(Verdict::Impossible, "沒有這個檔案".into()));
+ // Words without JSON: not yet, with what it said.
+ assert_eq!(read_verdict("I think it is done"), Judged::Said(Verdict::NotYet, "I think it is done".into()));
+ assert!(matches!(read_verdict(""), Judged::Said(Verdict::NotYet, r) if !r.is_empty()));
+ }
+
+ #[test]
+ fn not_yet_goes_again_until_the_brakes() {
+ let mut g = Goal::new("測試通過", 0);
+ let not_yet = || Judged::Said(Verdict::NotYet, "還有 1 個失敗".into());
+ g.after_turn(true);
+ assert_eq!(after_verdict(&mut g, not_yet(), 60_000), Next::Again { text: "[目標]還沒達成:還有 1 個失敗".into() });
+ assert_eq!((g.turns, g.reason.as_str(), g.active()), (1, "還有 1 個失敗", true));
+ // Turns that do nothing: it stops after IDLE_TURNS of them.
+ for _ in 1..IDLE_TURNS {
+ g.after_turn(false);
+ assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Again { .. }));
+ }
+ g.after_turn(false);
+ assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Pause { .. }));
+ assert!(!g.active());
+ // The person writes: it goes on.
+ g.resume();
+ assert!(g.active() && g.idle == 0);
+ // The turn cap: stops at `until`, and a message gives it TURNS more.
+ g.turns = TURNS - 1;
+ g.after_turn(true);
+ assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Pause { note, .. } if note.contains(&format!("{TURNS} 輪"))));
+ g.resume();
+ assert_eq!(g.until, TURNS * 2);
+ assert!(matches!(after_verdict(&mut g, not_yet(), 0), Next::Again { .. }));
+ }
+
+ #[test]
+ fn met_impossible_waiting_and_a_silent_judge() {
+ let mut g = Goal::new("測試通過", 0);
+ assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Met, "全部通過".into()), 125_000), Next::Over { note, .. } if note.contains("目標達成") && note.contains("全部通過") && note.contains("1 輪 · 2 分")));
+ let mut g = Goal::new("找到檔案", 0);
+ assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Impossible, "不存在".into()), 0), Next::Over { .. }));
+ let mut g = Goal::new("登入後下載", 0);
+ assert!(matches!(after_verdict(&mut g, Judged::Said(Verdict::Waiting, "等你登入".into()), 0), Next::Pause { .. }));
+ assert_eq!(g.paused, "等你回覆");
+ let mut g = Goal::new("x", 0);
+ assert!(matches!(after_verdict(&mut g, Judged::Failed("timeout".into()), 0), Next::Pause { .. }));
+ assert_eq!(g.turns, 0, "a check that didn't happen isn't a turn");
+ let mut g = Goal::new("x", 0);
+ assert!(after_trouble(&mut g, true).contains("停止") && !g.active());
+ }
+
+ #[test]
+ fn the_brief_reads_from_the_goal_on_and_keeps_the_newest() {
+ let old = Message { at: 5, ..Message::user("更早的事") };
+ let set = Message { at: 10, goal: "測試通過".into(), ..Message::user("/goal 測試通過") };
+ let call = Message { at: 11, tool_calls: vec![ToolCall { id: "1".into(), name: "shell".into(), args: r#"{"command":"cargo test"}"#.into(), status: Default::default() }], ..Message::assistant("跑測試", "") };
+ let out = Message { at: 12, ..Message::tool_result("1", "shell", &format!("{}\ntest result: ok. 3 passed", "x".repeat(5000))) };
+ let note = Message { at: 13, note: true, ..Message::assistant("目標暫停", "") };
+ let g = Goal::new("測試通過", 10);
+ let b = brief(&g, &[old, set, call, out, note], 70_010);
+ assert!(b.starts_with("目標:測試通過"));
+ assert!(b.contains("1 分") && b.contains("第 1 輪"));
+ assert!(!b.contains("更早的事"), "before the goal: not read");
+ assert!(b.contains("【bot 用了 shell】") && b.contains("cargo test"));
+ assert!(b.contains("test result: ok. 3 passed"), "a result's end is kept");
+ assert!(b.contains("中間省略"));
+ assert!(!b.contains("目標暫停"), "AnyBot's own lines aren't evidence");
+ // Long chats: the newest part.
+ let many: Vec = (0..200).map(|i| Message { at: 10 + i, ..Message::assistant(&format!("第{i}步 {}", "y".repeat(400)), "") }).collect();
+ let b = brief(&g, &many, 0);
+ assert!(b.contains("第199步") && !b.contains("第0步 ") && b.contains("省略"));
+ }
+
+ #[test]
+ fn a_restart_pauses_what_was_going_on() {
+ let mut gs = [Goal::new("a", 0), Goal { paused: "等你回覆".into(), ..Goal::new("b", 0) }];
+ assert!(pause_all(gs.iter_mut()));
+ assert_eq!(gs[0].paused, "AnyBot 重新啟動過");
+ assert_eq!(gs[1].paused, "等你回覆");
+ assert!(!pause_all(gs.iter_mut()));
+ }
+
+ #[test]
+ fn times_and_lines() {
+ assert_eq!(elapsed(40_000), "40 秒");
+ assert_eq!(elapsed(12 * 60_000 + 5_000), "12 分");
+ assert_eq!(elapsed(3_600_000), "1 小時");
+ assert_eq!(elapsed(3_900_000), "1 小時 5 分");
+ let g = Goal { turns: 3, ..Goal::new("x", 0) };
+ assert_eq!(bar_text(&g, 120_000), "目標進行中 · 2 分 · 3 輪");
+ assert!(status(None, 0).contains("沒有設定目標"));
+ assert!(status(Some(&g), 0).contains("目前的目標:x"));
+ let set = Message { goal: "x".into(), ..Message::user("/goal x") };
+ assert!(context_line(&set).unwrap().contains("使用者用 /goal 設了目標"));
+ let again = Message { goal: "x".into(), wake: true, ..Message::user("[目標]還沒達成:y") };
+ assert!(context_line(&again).unwrap().contains("還沒達成"));
+ assert_eq!(context_line(&Message::user("hi")), None);
+ }
+}
diff --git a/src/icons.rs b/src/icons.rs
index 4837f0e..924f6dc 100644
--- a/src/icons.rs
+++ b/src/icons.rs
@@ -85,6 +85,7 @@ pub enum Icon {
ChevronRight,
Bookmark,
Brain,
+ Target,
}
impl Icon {
@@ -176,6 +177,7 @@ impl Icon {
Icon::ShoppingBag => include_str!("../icons/lucide/shopping-bag.svg"),
Icon::Message => include_str!("../icons/lucide/message-circle.svg"),
Icon::Alarm => include_str!("../icons/lucide/alarm-clock.svg"),
+ Icon::Target => include_str!("../icons/lucide/target.svg"),
Icon::CircleCheck => include_str!("../icons/lucide/circle-check.svg"),
Icon::CircleX => include_str!("../icons/lucide/circle-x.svg"),
Icon::Minus => include_str!("../icons/lucide/minus.svg"),
diff --git a/src/main.rs b/src/main.rs
index 7b8d534..6542efc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -59,6 +59,7 @@ mod theme;
mod tools;
mod triggers;
mod embed;
+mod goal;
mod store;
mod docindex;
mod drops;
diff --git a/src/model.rs b/src/model.rs
index 106308a..5d79e5a 100644
--- a/src/model.rs
+++ b/src/model.rs
@@ -92,6 +92,14 @@ pub struct Message {
/// `memories` is decided (picked by the person, or chosen once): don't choose again.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub memories_set: bool,
+ /// 目標 (/goal): the goal this message works toward — the person's 「/goal …」, or AnyBot's
+ /// 「還沒達成」 that starts the next turn. The model reads it after the words (goal::context_line).
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub goal: String,
+ /// A line AnyBot itself wrote in the chat (how a goal stands): shown small in the middle,
+ /// never sent to the model.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub note: bool,
/// What the model reads after the person's words (送出時間, the memories): made by
/// app::group_history from the fields above, never saved.
#[serde(skip)]
@@ -255,6 +263,10 @@ pub struct Bot {
pub routines: Vec,
#[serde(default)]
pub last_turn: Option,
+ /// 目標 (/goal): what it keeps working toward, turn after turn, until a check says it holds.
+ /// The brain's alone (a turn's end changes it); see goal.rs.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub goal: Option,
/// Name of the computer tools use unless told otherwise.
#[serde(default = "default_computer")]
pub default_computer: String,
@@ -793,6 +805,7 @@ impl State {
context_tokens: default_context_tokens(),
routines: vec![],
last_turn: None,
+ goal: None,
default_computer: default_computer(),
};
let mut helper = mk(5, "電腦助手", "幫你整理檔案、跑指令。動手前會先問你。", "gem", "blue", ProviderKind::Anthropic, true);
diff --git a/src/providers.rs b/src/providers.rs
index b9267a6..407669f 100644
--- a/src/providers.rs
+++ b/src/providers.rs
@@ -217,6 +217,8 @@ pub enum StreamEvent {
/// 自己進化: after the turn, the way that worked was kept as a skill (with the time of the
/// reply it learned from, which gets a line saying so).
Learned(crate::memory::Skill, i64),
+ /// 目標: the check after a turn has spoken (for the goal set at this time, ms).
+ Goal(i64, crate::goal::Judged),
Done,
Error(String),
}
diff --git a/src/remote.rs b/src/remote.rs
index f87eb6d..632fb66 100644
--- a/src/remote.rs
+++ b/src/remote.rs
@@ -327,6 +327,7 @@ pub fn message_json(m: &crate::model::Message, names: &HashMap, pag
"summary": m.summary,
"interrupted": m.interrupted,
"wake": m.wake,
+ "note": m.note,
"author": if m.author == 0 { String::new() } else { names.get(&m.author).cloned().unwrap_or_default() },
"reactions": m.reactions,
"attachments": m.attachments.iter().map(|a| json!({"name": a.name, "image": a.image, "path": a.path})).collect::>(),
diff --git a/src/setup.rs b/src/setup.rs
index ad436ec..0d117d2 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1158,6 +1158,7 @@ fn seed_first() -> i32 {
context_tokens: crate::agent::DEFAULT_CONTEXT_TOKENS,
routines: vec![],
last_turn: None,
+ goal: None,
default_computer: crate::model::default_computer(),
});
st.primary_bot = 1;